我收到了一个有效负载,我需要从有效负载内的两个不同级别提取 ID,并将其作为键值对的单个对象返回。我试图进行某种组合或 ForEach()
和 reduce()
但我似乎找不到正确的方法。这是数据的样子。
{
orderId:999,
menuId: 123456,
questions:[{
questionId: 123,
depth: 1,
answers: [
{ answerId: 999, text: "foo1" },
{ answerId: 888, text: "foo2" }]
},
{
questionId: 654,
depth: 1,
answers: [{ answerId: 777, text: "bar" }]
}]
}
我想要得到什么结果
{"q_123": ["999", "888"], "q_654": "777"}
最佳答案
以下使用reduce
的方法可以完成这项工作:
const data = {
orderId: 999,
menuId: 123456,
questions: [{
questionId: 123,
depth: 1,
answers: [{
answerId: 999,
text: "foo1"
}, {
answerId: 888,
text: "foo2"
}
]
}, {
questionId: 654,
depth: 1,
answers: [{
answerId: 777,
text: "bar"
}]
}
]};
const result = data.questions.reduce((all, {
questionId: id,
answers
}) => {
all[`q_${id}`] = answers.map(a => a.answerId);
return all;
}, {});
console.log(result);
关于javascript从两级数组中提取id以获取新对象中的键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51071302/