I need to flatten nested object to an array of objects. So far this is what i came up with. But it is not working properly. Currently I'm checking the current element is object or not, if it is an object I'm calling same function recursively.
As the output i need this.
[
{title: 'Foo', value: 111},
{title: 'Bar', value: 222},
...
]
var data = {
1: {
title: "Foo",
value: 111,
children: {
2: {
title: "Bar",
value: 222,
},
},
},
3: {
title: "Baz",
value: 333,
children: {
4: {
title: "Qux",
value: 444,
children: {
5: {
title: "Quux",
value: 555,
},
},
},
},
},
};
const finalArrayOfObjects = [];
const flattenObject = (obj) => {
const flattened = {};
Object.keys(obj).forEach((key) => {
if (typeof obj[key] === "object" && obj[key] !== null) {
flattenObject(obj[key]);
} else {
flattened[key] = obj[key];
}
finalArrayOfObjects.push(flattened);
console.log(flattened);
});
};