gpt4 book ai didi

javascript - 需要功能帮助处理此数据结构

转载 作者:行者123 更新时间:2023-11-30 15:23:26 25 4
gpt4 key购买 nike

我有这个数据结构:

let questions=[{
question: "What is your name?",
responses: [{
userId: 1,
answer: "Geof"
}, {
userId: 5,
answer: "Pete"
}]
}, {
question: "Where are you from?",
responses: [{
userId: 3,
answer: "Earth"
}, {
userId: 5,
answer: "Mars"
}]
},.......]

我想将这个对象传播到:

[{ userId: 1, "What is your name?": "geoff", "Where are you from?":"", "another question":....}, 
{ userId: 2, "What is your name?": "", "Where are you from?":"".......}

由于我无法预测我会收到哪些问题,所以我正在寻找一个以这种方式传播问题的动态函数。非常欢迎使用 lodash 的解决方案。

最佳答案

let questions=[{
question: "What is your name?",
responses: [{
userId: 1,
answer: "Geof"
}, {
userId: 5,
answer: "Pete"
}]
}, {
question: "Where are you from?",
responses: [{
userId: 3,
answer: "Earth"
}, {
userId: 5,
answer: "Mars"
}]
}]

var responses = {}
questions.forEach(q => q.responses.forEach(res => (responses[res.userId] = responses[res.userId] || {})[q.question] = res.answer))
console.log(responses)

//If you really want it as array :

var arr = [];
for (var userId in responses) {
responses[userId].userId = userId;
arr.push(responses[userId]);
}

console.log(arr)

请注意,这不会存储诸如“你叫什么名字?”:“”之类的内容,但这是不必要的,您可以使用 hasOwnProperty 检查用户是否回答了该问题

关于javascript - 需要功能帮助处理此数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43349787/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com