I wanted to know what is the best way to extract the same named object from a multi level nested object.
I currently have an object that looks like this, and i want to extract out the parentLocationCluster objects out of it.
const foo = {
id: '1',
name: 'boo',
parentLocationCluster: {
id: 1,
name: 'foo',
parentLocationCluster: {
id: 2,
name: 'fii',
parentLocationCLuster: {
id: 3,
name: 'faa',
},
},
},
};
Now I could just a nested if statement like so:
const { parentLocationCluster } = foo;
if(parentLocationCluster) {
//do something
if(parentLocationCluster.parentLocationCluster) {
//do something
}
}
but i feel this is significantly inefficient ( which is what i am doing at the moment). Also, the objects could vary with the number of nested parentLocationCluster objects i.e. an object could contain 10 levels of parentLocationClusters.
What would be the best way to do this?
parentLocationCluster? Do you want to know if there arexlevels ofparentLocationClusters? Do you...? - Please be more specific on the actual use case.