access nested object propertyy [][] code example
Example 1: Accessing Nested Objects
var myStorage = {
"car": {
"inside": {
"glove box": "maps",
"passenger seat": "crumbs"
},
"outside": {
"trunk": "jack"
}
}
};
var gloveBoxContents = myStorage.car.inside["glove box"];
console.log(gloveBoxContents);
Example 2: access to nested properties on javascript using property names
const getNestedObject = (nestedObj, pathArr) => {
return pathArr.reduce((obj, key) =>
(obj && obj[key] !== 'undefined') ? obj[key] : undefined, nestedObj);
}
const name = getNestedObject(user, ['personalInfo', 'name']);
const city = getNestedObject(user, ['personalInfo', 'addresses', 0, 'city']);