首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将特定问题排序到特定部分?

如何将特定问题排序到特定部分?
EN

Stack Overflow用户
提问于 2021-07-30 16:27:38
回答 3查看 73关注 0票数 0

我从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]}]如果有任何帮助,我们将不胜感激

EN

回答 3

Stack Overflow用户

发布于 2021-07-30 17:05:54

从你添加的评论中,我希望sectionquestionsMergedArray的结构如下

代码语言:javascript
复制
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']
    }
];

请在下面找到生成它们的解决方案。我已经为代码功能添加了注释。

代码语言:javascript
复制
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);

票数 1
EN

Stack Overflow用户

发布于 2021-07-30 17:08:38

一个通用的解决方案:

代码语言:javascript
复制
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);

票数 1
EN

Stack Overflow用户

发布于 2021-07-30 17:58:44

假设对象是@Nitheesh设置的,这里有一种通过对象操作以及Array.reduce()Array.filter()方法获得答案的方法。

代码语言:javascript
复制
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. 创建

的截面对象键的数组

代码语言:javascript
复制
const sectionKeys = Object.keys(section);
// [ 'section-1', 'section-2', 'section-3'] 

  1. 使用Array.reduce()创建一个对象,其中的键等于每个节号(注释中包含了其中的步骤)

代码语言:javascript
复制
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输出:

代码语言:javascript
复制
{
    "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. 现在我们不再需要密钥了,所以我们只得到

的值

代码语言:javascript
复制
const final = Object.values(reducedObject);

最终输出:

代码语言:javascript
复制
[
    {
        "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()方法,所以我想打破这些步骤,希望能帮助其他可能需要它的人。

查看下面的工作代码片段:

代码语言:javascript
复制
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);

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68594252

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档