Reputation: 3856
I have this data structure:
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"
}]
},.......]
I would like to spread this object to:
[{ userId: 1, "What is your name?": "geoff", "Where are you from?":"", "another question":....},
{ userId: 2, "What is your name?": "", "Where are you from?":"".......}
Since I cannot predict what questions that I get, I am looking for a dynamic function that spreads it this way. A solution with lodash is highly welcome.
Upvotes: 1
Views: 50
Reputation: 24979
What about:
function formatAnswers(qs) {
// Format into a map
let users = {};
qs.forEach((q) => {
q.responses.forEach((r) => {
if (users[r.userId] === undefined) {
users[r.userId] = {
userId: r.userId,
[q.question]: r.answer
};
} else {
users[r.userId][q.question] = r.answer;
}
});
});
// Transform map into an array
let out = [];
for (var entry in users) {
out.push(users[entry]);
}
return out;
}
let result = formatAnswers(questions);
console.log(result);
Upvotes: 1
Reputation: 16068
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)
Note that this won´t store things like "What is your name?": "" but that is unnecesary, you can check with hasOwnProperty if a user has answered that question or not
Upvotes: 1