我从API获取数据,并能够将从API接收到的大量数据排序到两个数组中。一个名为sections的数组和一个名为questions的数组。因此sections数组看起来是这样的:
const section = section-1: some_title,section-2:some_title,section-3:some_title,问题数组如下:
常量问题=Q1-1:某问题,Q1-2:某问题,Q1-3:某问题,Q2-1:某问题,Q2-2:某问题,Q2-3:某问题,Q3-1:某问题,Q3-2:某问题,Q3-3:某问题,Q3-3:某问题
我想要做的是将两个数组合并在一起,并按如下方式对它们进行排序:const MergedArray = [{section-1: some_title, questions: [ Q1-1:some_question,Q1-2:some_question,Q1-3:some_question]},{section-2:some_title, questions: [Q2-1:some_question,Q2-2:some_question,Q2-3:some_question]},{section-3:some_title, questions: [Q3-1:some_question,Q3-2:some_question,Q3-3:some_question]}]如果有任何帮助,我们将不胜感激
发布于 2021-07-30 17:05:54
从你添加的评论中,我希望section,questions和MergedArray的结构如下
const section = [
'section-1:some_title',
'section-2:some_title',
'section-3:some_title',
];
const questions = [
'Q1-1:some_question',
'Q1-2:some_question',
'Q1-3:some_question',
'Q2-1:some_question',
'Q2-2:some_question',
'Q2-3:some_question',
'Q3-1:some_question',
'Q3-2:some_question',
'Q3-3:some_question',
]
const MergedArray = [
{
'section-1': 'some_title',
questions: [ 'Q1-1:some_question','Q1-2:some_question','Q1-3:some_question']
},
{
'section-2':'some_title',
questions: ['Q2-1:some_question','Q2-2:some_question','Q2-3:some_question']
},
{
'section-3':'some_title',
questions: ['Q3-1:some_question','Q3-2:some_question','Q3-3:some_question']
}
];请在下面找到生成它们的解决方案。我已经为代码功能添加了注释。
const section = [
'section-1:some_title',
'section-2:some_title',
'section-3:some_title',
];
const questions = [
'Q1-1:some_question',
'Q1-2:some_question',
'Q1-3:some_question',
'Q2-1:some_question',
'Q2-2:some_question',
'Q2-3:some_question',
'Q3-1:some_question',
'Q3-2:some_question',
'Q3-3:some_question',
]
const MergedArray = section.reduce((accumulator, currentValue) => {
const node = {};
const [key, value] = currentValue.split(':');
// This will generate
// key = 'section-1' and value='some_title' for first itration
// key = 'section-2' and value='some_title' for second itration
// key = 'section-3' and value='some_title' for third itration
node[key] = value;
// this will update node object as
// node = {'section-1': 'some_title'} for first itration
// node = {'section-2': 'some_title'} for second itration
// node = {'section-3': 'some_title'} for third itration
const sectionIndex = key.split('-')[1];
// sectionIndex will be
// 1 for first itration
// 2 for second itration
// 3 for third itration
// Now you have to pick questions from questions array.
// Questions For section-1 are 'Q1-1:some_question', 'Q1-2:some_question', 'Q1-3:some_question',
// Questions For section-2 are 'Q2-1:some_question', 'Q2-2:some_question', 'Q2-3:some_question',
// Questions For section-3 are 'Q3-1:some_question', 'Q3-2:some_question', 'Q3-3:some_question',
// So you have to flter out the questions from the array.
// `Q${sectionIndex}-` is string manipulation. This will generate 'Q1-', 'Q2-', 'Q3-'.
// You have to filter out questions staring with these strings.
// i.e, their respective index should be zero in the matching words from that array
// The below expression will filter out questions starting with
// 'Q1-' in the first itration
// 'Q2-' in the second itration
// 'Q3-' in the third itration
const questionList = questions.filter((ques) => ques.indexOf(`Q${sectionIndex}-`) === 0);
// this will make
// questionList = [ 'Q1-1:some_question', 'Q1-2:some_question', 'Q1-3:some_question'] in the first itration
// questionList = [ 'Q2-1:some_question', 'Q2-2:some_question', 'Q2-3:some_question'] in the second itration
// questionList = [ 'Q3-1:some_question', 'Q3-2:some_question', 'Q3-3:some_question'] in the third itration
node.questions = questionList;
// This will update node as
// node = {'section-1': 'some_title' questions: [ 'Q1-1:some_question', 'Q1-2:some_question', 'Q1-3:some_question']} in the first itration
// node = {'section-2': 'some_title' questions: [ 'Q2-1:some_question', 'Q2-2:some_question', 'Q2-3:some_question']} in the second itration
// node = {'section-3': 'some_title' questions: [ 'Q3-1:some_question', 'Q3-2:some_question', 'Q3-3:some_question']} in the third itration
accumulator.push(node);
return accumulator;
}, []);
console.log(MergedArray);
发布于 2021-07-30 17:08:38
一个通用的解决方案:
const section = [{"section-1": "some_title"}, {"section-2":"some_title"}, {"section-3":"some_title"}];
const questions = [{"Q1-1":"some_question"}, {"Q1-2":"some_question"}, {"Q1-3":"some_question"}, {"Q2-1":"some_question"}, {"Q2-2":"some_question"}, {"Q2-3":"some_question"}, {"Q3-1":"some_question"}, {"Q3-2":"some_question"}, {"Q3-3":"some_question"}];
let obj = {};
for(let ques of questions){
let key = Object.keys(ques)[0].split("-")[0].toLowerCase();
obj[key] = (obj[key] || []).concat(ques);
}
let result = [];
for(let sec of section){
let key = "q" + Object.keys(sec)[0].split("-")[1];
result.push({...sec, questions: obj[key]})
}
console.log(result);
发布于 2021-07-30 17:58:44
假设对象是@Nitheesh设置的,这里有一种通过对象操作以及Array.reduce()和Array.filter()方法获得答案的方法。
const reduced = Object.values(
Object.keys(section).reduce((acc, cur) => {
const num = cur.split('-')[1]
acc[num] = acc[num] || {};
acc[num][cur] = section[cur];
acc[num].questions = Object.fromEntries(
Object.entries(questions)
.filter(([key, value]) => key.substr(1, 1) == num));
return acc;
}, {})
);我将详细介绍每一步,以帮助可视化正在发生的事情
的截面对象键的数组
const sectionKeys = Object.keys(section);
// [ 'section-1', 'section-2', 'section-3'] Array.reduce()创建一个对象,其中的键等于每个节号(注释中包含了其中的步骤)const reducedObject = sectionKeys.reduce((acc, cur) => {
//Get the section number from the current value
const num = cur.split('-')[1]
//Check if the key exists in the accumulator obj. If not return an empty object
acc[num] = acc[num] || {}; //acc = { 1: {}, 2: {}, 3: {} }
//Get from the 'section' obj the value where the Key is the current value
acc[num][cur] = section[cur]; //acc = { "1":{"section-1":"some_title"},
// "2":{"section-2":"some_title"}, "3":{"section-3":"some_title"} }
//Convert the 'questions' object variable into an array of [key, val] arrays
const arrayKeyVals = Object.entries(questions); //arrayKeyVals = [
// ["Q1-1","some_question"],["Q1-2","some_question"],["Q1-3","some_question"],
// ["Q2-1","some_question"],["Q2-2","some_question"],["Q2-3","some_question"],
// ["Q3-1","some_question"],["Q3-2","some_question"],["Q3-3","some_question"]]
//Filter the array of arrays where the 2nd char of the key == the 'num' variable
const filteredArray = arrayKeyVals
.filter(([key, value]) => key.substr(1, 1) == num); //When num==1:
// [["Q1-1","some_question"],["Q1-2","some_question"],["Q1-3","some_question"]]
//Convert filteredArray back into an object
const objQuestions= Object.fromEntries(filteredArray); //When num==1:
// {"Q1-1":"some_question","Q1-2":"some_question","Q1-3":"some_question"}
//Assign the filtered questions object
acc[num].questions = objQuestions;
return acc; //return the accumulator
}, {})步骤2输出:
{
"1": {
"section-1": "some_title",
"questions": {
"Q1-1": "some_question",
"Q1-2": "some_question",
"Q1-3": "some_question"
}
},
"2": {
"section-2": "some_title",
"questions": {
"Q2-1": "some_question",
"Q2-2": "some_question",
"Q2-3": "some_question"
}
},
"3": {
"section-3": "some_title",
"questions": {
"Q3-1": "some_question",
"Q3-2": "some_question",
"Q3-3": "some_question"
}
}
}的值
const final = Object.values(reducedObject);最终输出:
[
{
"section-1": "some_title",
"questions": {
"Q1-1": "some_question",
"Q1-2": "some_question",
"Q1-3": "some_question"
}
},
{
"section-2": "some_title",
"questions": {
"Q2-1": "some_question",
"Q2-2": "some_question",
"Q2-3": "some_question"
}
},
{
"section-3": "some_title",
"questions": {
"Q3-1": "some_question",
"Q3-2": "some_question",
"Q3-3": "some_question"
}
}
]我希望这不是TMI。我花了一段时间才掌握了Array.reduce()方法,所以我想打破这些步骤,希望能帮助其他可能需要它的人。
查看下面的工作代码片段:
const section = {
'section-1': 'some_title',
'section-2': 'some_title',
'section-3': 'some_title'
};
const questions = {
'Q1-1': 'some_question',
'Q1-2': 'some_question',
'Q1-3': 'some_question',
'Q2-1': 'some_question',
'Q2-2': 'some_question',
'Q2-3': 'some_question',
'Q3-1': 'some_question',
'Q3-2': 'some_question',
'Q3-3': 'some_question'
};
const reduced = Object.values(
Object.keys(section).reduce((acc, cur) => {
const num = cur.split('-')[1]
acc[num] = acc[num] || {};
acc[num][cur] = section[cur];
acc[num].questions = Object.fromEntries(
Object.entries(questions)
.filter(([key, value]) => key.substr(1, 1) == num));
return acc;
}, {})
);
const pre = document.createElement('pre');
pre.innerText = JSON.stringify(reduced, null, 2);
document.querySelector('body').appendChild(pre);
https://stackoverflow.com/questions/68594252
复制相似问题