Safely setting object properties with dot notation strings in JavaScript

JavascriptFront End TechnologyObject Oriented Programming

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

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

Example

let _ = require("lodash");
let obj = {
   a: {
      b: {
         foo: "test"
      },
      c: 2
   }
};
_.set(obj, "a.b.foo", "test1");
_.set(obj, "a.c", { test2: "bar" });
console.log(obj);

Output

This will give the output −

{ a: { b: { foo: 'test1' }, c: { test2: 'bar' } } }

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

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

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

Example

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

Output

This will give the output −

{ level1: { level2: 'FooBar', anotherLevel2: 'bar' } }
raja
Published on 27-Nov-2019 15:00:28
Advertisements