2017-11-08 7 views
1

제목이 더 복잡해 보일 수 있습니다.두 개체 목록을 개체 목록으로 병합하는 방법

2 개의 다른지도로 작성된 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"}] 

답변

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

, 감사합니다! – StackBeginnerThanks

0

당신은 questions의 각 통해 서로를 반복하고 .forEach()를 사용하여 병합 할 수 있습니다 :

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

도 작동했습니다. 감사합니다. – StackBeginnerThanks

0

당신은 임의 걸릴 수 : 출력

let questions = [ 
{question: "Question?"}, 
{question: "Question 2"}, 
]; 

let answers = [ 
{answer: "Yes"}, 
{answer: "no"} 
]; 

questions.forEach((question, i) => question["answer"] = Object.values(answers[i])[0]); 

prope의 수 rties 및 원하는 배열을 만들고 새 객체를 만듭니다. 이 일

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