Answers for "access to nested properties on javascript using property names"

0

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);
}

// pass in your object structure as array elements
const name = getNestedObject(user, ['personalInfo', 'name']);

// to access nested array, just pass in array index as an element the path array.
const city = getNestedObject(user, ['personalInfo', 'addresses', 0, 'city']);
// this will return the city from the first address item.
Posted by: Guest on February-10-2021

Code answers related to "access to nested properties on javascript using property names"

Code answers related to "Javascript"

Browse Popular Code Answers by Language