let's say I have this object:
let obj = {
name: "John",
location: {
country: "France",
town: "Paris",
street: { number: 23, name: "Napoleon" },
},
};
let streetNumber = obj.location.street.number;
Is there a simpler method to get the street number without writing that big line of code "obj.location.street.number"? Imagine if I would have 10 levels in a nested object. Actually I have a very very big object with unique keys and it takes too much time to write that chain until I get the desired value.
CodePudding user response:
you can do something like this, but I don't suggest you, it's better to go property by property, like you did.
function recursion(obj) {
for (const prop in obj) {
if (obj.hasOwnProperty(prop)) {
if (typeof obj[prop] == 'object') return recursion(obj[prop])
if (prop == 'number') return obj[prop]
}
}
}
CodePudding user response:
I think you may have to create a function for simplicity.
const getStreetNumber = (obj) => obj["location"]["street"]["number"];