I have an array:
let testData = [
{
MC: "11233",
jobid: 113331,
list: [
{ Q1: 1113, Q2: 333, code: "thisis1" },
{ Q1: 333, Q2: 111, code: "thisis2" },
{ Q1: 333, code: "thisis3" },
],
},
{
MC: "332211",
jobid: 3333,
list: [
{ Q1: 444, Q2: 555, code: "thisis4" },
],
},
];
And I want to convert it into:
[
{ MC: "11233", jobid: 113331, Q1: 1113, Q2: 333, code: "thisis1" },
{ MC: "11233", jobid: 113331, Q1: 333, Q2: 111, code: "thisis2" },
{ MC: "11233", jobid: 113331, Q1: 333, code: "thisis3" },
{ MC: "332211", jobid: 3333, Q1: 444, Q2: 555, code: "thisis4" },
]
I tried to write a recursive function like this
let newData = [];
testData.forEach((element, index) => {
let flattedObj = {};
deconstructeArrayObject(flattedObj, element);
});
and
const deconstructeArrayObject = (flattedObj, targetObj) => {
let tempArr = [];
for (let key in targetObj) {
if (Array.isArray(targetObj[key])) {
targetObj[key].forEach((element) => {
tempArr.push(
...JSON.parse(
JSON.stringify(
deconstructeArrayObject(flattedObj, element, outputArray)
)
)
);
});
} else {
flattedObj[key] = targetObj[key];
}
}
return flattedObj; // actually I want this function to return an array
};
I have no idea how should I reach my goal. Is there any hint or suggestion?