【问题标题】:How to merge two lists of objects into 1 list of objects while also merging the objects如何在合并对象的同时将两个对象列表合并为一个对象列表
【发布时间】:2018-04-21 12:27:56
【问题描述】:

标题听起来可能比实际复杂。

我有 2 个数组,由两个不同的地图创建。然后我继续循环遍历每个数组,如下所示:

let temp = [];
    let temp2 = [];

    nameArray.forEach(function(x){
        temp.push({question: x[0]})
    })
    bodyArray.forEach(function(x){
        temp2.push({answer: x[0]})
    })

给我以下结果:

[0:{question: "generic question"}
 1:{question:...}
 2:{...}]

和:

[0:{answer: "generic answer"}
 1:{answer:...}
 2:{...}]

我最终希望得到的是一个对象列表,并且对象是两个数组中的对象,但是像这样合并:

[0:{question: "generic question", answer: "generic answer"}]

【问题讨论】:

    标签: javascript arrays merge javascript-objects


    【解决方案1】:

    您可以使用array#map 并遍历您的问题数组,通过使用question 数组的索引,您可以从answer 数组中添加元素并生成包含问题和答案的对象数组。

    const questions = ["generic question", "generic question 12", "generic question 34"],
          answers = ["generic answer", "generic answer 12", "generic answer 34"];
    
    const merged = questions.map((question, i) => ({question, 'answer' : answers[i]}));
    console.log(merged);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    【讨论】:

      【解决方案2】:

      您可以遍历每个 questions 并使用 .forEach() 合并它们:

      let questions = [
      {question: "Question?"},
      {question: "Question 2"},
      ];
      
      let answers = [
      {answer: "Yes"},
      {answer: "no"}
      ];
      
      questions.forEach((question, i) => question["answer"] = Object.values(answers[i])[0]);
      

      哪些输出:

       [ 0: {question: "Question?", answer: "Yes"},
      1: {question: "Question 2", answer: "no"} ]
      

      【讨论】:

        【解决方案3】:

        您可以获取任意数量的属性和所需的数组并构建新对象。

        var questions = ['question1', 'question2', 'question3'],
            answers = ['answer1', 'answer2', 'answer3'],
            keys = ['question', 'answer'],
            result = [questions, answers].reduce(function (r, a, i) {
                a.forEach(function (v, j) {
                    r[j] = r[j] || {};
                    r[j][keys[i]] = v;
                });
                return r;
            }, []);
        
        console.log(result);
        .as-console-wrapper { max-height: 100% !important; top: 0; }

        【讨论】:

          猜你喜欢
          • 2021-10-29
          • 2019-09-08
          • 1970-01-01
          • 2021-09-10
          • 1970-01-01
          • 1970-01-01
          • 2017-03-23
          • 1970-01-01
          相关资源
          最近更新 更多