I need to convert a deeply nested object of objects into an array of objects for each level until it has no more "parents"
I am receiving an object like this:
{
name: '1',
address: '1',
parent: {
name: '2',
address: '2',
parent: {
name: '3',
address: '3',
parent: {
name: '4',
address: '4',
parent: {
name: '5',
address: '5',
parent: null,
},
},
},
},
},
The expected result would be something like this:
[
{ name: '1', address: '1',},
{ name: '2', address: '2',},
{ name: '3', address: '3',},
{ name: '4', address: '4',},
{ name: '5', address: '5',},
]
I looked everywhere but I couldn't find a simple and reliable solution.
Any suggestion will be appreciated.
CodePudding user response:
Here's a recursive option which utilizes the flat
method to make things simpler:
const data = {
name: '1',
address: '1',
parent: {
name: '2',
address: '2',
parent: {
name: '3',
address: '3',
parent: {
name: '4',
address: '4',
parent: {
name: '5',
address: '5',
parent: null,
},
},
},
},
};
const flattenObject = (acc, curr) => curr.parent ? [...acc, {
name: curr.name,
address: curr.address
}, flattenObject(acc, curr.parent)].flat() : [...acc, {
name: curr.name,
address: curr.address
}];
const flatData = flattenObject([], data);
console.log(flatData);