access to nested properties on javascript using property names

Solutions on MaxInterview for access to nested properties on javascript using property names by the best coders in the world

we are a community of more than 2 million smartest coders
registration for
employee referral programs
are now open
get referred to google, amazon, flipkart and more
register now
  
pinned-register now
showing results for - "access to nested properties on javascript using property names"
Ignacio
19 Jan 2019
1const getNestedObject = (nestedObj, pathArr) => {
2    return pathArr.reduce((obj, key) =>
3        (obj && obj[key] !== 'undefined') ? obj[key] : undefined, nestedObj);
4}
5
6// pass in your object structure as array elements
7const name = getNestedObject(user, ['personalInfo', 'name']);
8
9// to access nested array, just pass in array index as an element the path array.
10const city = getNestedObject(user, ['personalInfo', 'addresses', 0, 'city']);
11// this will return the city from the first address item.
12
similar questions