如何将特定的问题分类到特定的部分?



我从API获取数据,并且能够将从API接收到的大数据分类到两个数组中。一个叫做sections的数组和一个叫做questions的数组。所以section数组看起来是这样的:

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, Q1-1:some_question, Q2-2:some_question, Q2-3:some_question, Q2-3:some_question, Q1-1:some_question, Q2-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"}];
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);

从您补充的评论中,我希望section,questionsMergedArray的结构如下

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);

假设对象是@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;
}, {})
);

我将把每一步分开来帮助想象发生了什么


  1. 创建一个section对象键的数组
const sectionKeys = Object.keys(section);
// [ 'section-1', 'section-2', 'section-3'] 
  1. 使用Array.reduce()创建一个对象,键等于每个section号(步骤内包含在注释中)
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"
}
}
}
  1. 现在我们不再需要键,所以我们只得到值
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);

最新更新