英文:
How to combine data from an array and object and put together into an array in JavaScript?
问题
arr = ["Q1A1", "Q2A3"]
假设Q1是问题1,A1是从问题中选择的选项。以下是对应Q1的对象,其中包含有关答案的详细信息,并且随着我们转到Q2,此对象也会更改。
{
id: "Q1",
answers: [
{
id: "Q1A1",
text: "是"
},
{
id: "Q1A2",
text: "否"
}
]
}
同样,如果我们在Q1中选择答案,对于Q2,我们有另一个对象。
{
id: "Q2",
answers: [
{
id: "Q2A1",
text: "测试1"
},
{
id: "Q2A2",
text: "测试2"
},
{
id: "Q2A3",
text: "测试3"
},
{
id: "Q2A4",
text: "测试4"
}
]
}
我需要通过包含问题和答案(例如,“Q1A1”)的数组查找对象,并找到所选答案的文本,即("是"),如果您查看上述问题1的对象。因此,我需要按以下方式放入数组中。
result = ["Q1_是", "Q2_测试3"]
英文:
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. The below array keep updated whenever we select an option from question.
arr = ["Q1A1", "Q2A3"]
assume Q1 is Question no. 1 and A1 is option selected from the question. 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
{
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
{
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 i.e ("Yes") if u look into the above object for question 1. Hence I need put into the array like this way.
result = ["Q1_Yes","Q2_Test3"]
答案1
得分: 1
这段代码将帮助您获取这些结果。
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)
请注意,我已经保留了代码的原始格式。
英文:
This code will help you to get those results.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
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)
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论