如何将两个对象列表合并为一个对象列表,同时合并对象

时间:2017-11-08 17:33:39

标签: javascript arrays merge javascript-objects

标题听起来可能比它复杂。

我有两个阵列,由两个不同的地图创建。然后我继续循环遍历每个数组:

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"}]

3 个答案:

答案 0 :(得分: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; }




答案 1 :(得分:0)

您可以对每个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"} ]

答案 2 :(得分:0)

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

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