Accessing nested JavaScript objects with string key


You can use lodash's get method to get properties at any level safely. Getting first-level properties is pretty straightforward. Nested property access is tricky and you should use a tested library like lodash for it.

You can access a deeply nested object in the following way −

Example

let _ = require("lodash");
let obj = {
   a: {
      b: {
         foo: "test"
      },
      c: 2
   }
};
console.log(_.get(obj, "a.b.foo"));
console.log(_.get(obj, "a.c"));
console.log(_.get(obj, "a.test"));
console.log(_.get(obj, "a.test.x"));

Output

This will give the output −

test
2
undefined
undefined

You can also write your own getProp function in the following way −

const getProp = (object, path) => {
   if (path.length === 1) return object[path[0]];
      else if (path.length === 0) throw error;
   else {
      if (object[path[0]]) return getProp(object[path[0]], path.slice(1));
      else {
         object[path[0]] = {};
         return getProp(object[path[0]], path.slice(1));
      }
   }
};

You can use it by passing an array to access the props.

Example

var obj = {
   level1:{
      level2:{
         level3:{
            name: "Foo"
         }
      },
      anotherLevel2: "bar"
   }
};
console.log(getProp(obj, ["level1", "level2"]));

Output

This will give the output −

{level3: {name: "Foo"}}

Updated on: 27-Nov-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements