简体   繁体   English

如何将数组和object中的数据合并到JavaScript中的数组中?

[英]How to combine data from an array and object and put together into an array in JavaScript?

I have an array in which I have some string value holding the id along with answer selected and I have different object in which I have the detail about answer which is selected.我有一个数组,其中我有一些字符串值保存 id 以及选择的答案,我有不同的 object,其中我有关于选择的答案的详细信息。 The below array keep updated whenever we select an option from question.每当我们 select 来自问题的选项时,下面的数组就会保持更新。

arr = ["Q1A1", "Q2A3"]

assume Q1 is Question no.假设 Q1 是问题号。 1 and A1 is option selected from the question. 1 和 A1 是从问题中选择的选项。 And below I have an object for the corresponding Q1 which contained the detail about answers and this object also get change as we move over to Q2下面我有一个对应 Q1 的 object,其中包含有关答案的详细信息,这个 object 在我们移至 Q2 时也会发生变化

{
id: "Q1",
answers: [
{
id: "Q1A1",
text: "Yes"
},
{
id: "Q1A2",
text: "No"
}  
]
}

same way I have any another object for Q2 if we select the answer in Q1, now we have different object for Q2同样,如果我们在 Q1 中的答案是 select,那么对于 Q2 我还有另一个 object,现在对于 Q2 我们有不同的 object

{
id: "Q2",
answers: [
{
id: "Q2A1",
text: "Test 1"
},
{
id: "Q2A2",
text: "Test 2"
},
{
id: "Q2A3",
text: "Test 3"
},
{
id: "Q2A4",
text: "Test 4"
}    
]
}

I need to lookup the object with the help of array which contain question and answer(eg, "Q1A1") with selected and need to find the text for answer selected ie ("Yes") if u look into the above object for question 1. Hence I need put into the array like this way.我需要在包含问题和答案(例如“Q1A1”)的数组的帮助下查找 object 并需要找到所选答案的文本,即(“是”)如果你查看上面的问题 1 object .因此我需要像这样放入数组中。

result = ["Q1_Yes","Q2_Test3"]

This code will help you to get those results.此代码将帮助您获得这些结果。

 let selected = ["Q1A1", "Q2A3"]; let QA = [ { id: "Q1", answers: [ { id: "Q1A1", text: "Yes" }, { id: "Q1A2", text: "No" } ] }, { id: "Q2", answers: [ { id: "Q2A1", text: "Test 1" }, { id: "Q2A2", text: "Test 2" }, { id: "Q2A3", text: "Test 3" }, { id: "Q2A4", text: "Test 4" } ] } ]; let all_answers = QA.reduce((allanswers,qa)=>(qa.answers.map(d=> allanswers[d.id]=[qa.id,d.text]),allanswers),{}); const result = selected.map(selected => all_answers[selected].join('_')) console.log(result)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM