How to use reduce method by loadash for nested/complex object
You can achieve it only using Javascript using Object.values and Array.prototype.map.
Using Array.map
const data = { Question1: { question: "Question1", answer: { Answer1: { answer: "Answer1_1", }, Answer2: { answer: "Answer1_2", }, }, }, Question2: { question: "Question2", answer: { Answer1: { answer: "Answer2_1", }, Answer2: { answer: "Answer2_2", }, }, }, };
const output = Object.values(data).map(({ question, answer }) => {
return {
question,
answer: Object.values(answer).map(({ answer }) => answer),
};
});
console.log(output);
Using Array.reduce
const data = { Question1: { question: "Question1", answer: { Answer1: { answer: "Answer1_1", }, Answer2: { answer: "Answer1_2", }, }, }, Question2: { question: "Question2", answer: { Answer1: { answer: "Answer2_1", }, Answer2: { answer: "Answer2_2", }, }, }, };
const output = Object.values(data).reduce((prev, { question, answer }) => {
prev.push({
question,
answer: Object.values(answer).reduce((prevVal, { answer }) => {
prevVal.push(answer);
return prevVal;
}, []),
});
return prev;
}, []);
console.log(output);