Safely setting object properties with dot notation strings in JavaScript

In JavaScript, safely setting nested object properties can be challenging because accessing undefined nested paths throws errors. This article covers two approaches: using Lodash's set method and creating a custom solution.

Using Lodash's set() Method

Lodash provides a safe set method that handles nested property assignment without throwing errors, even if intermediate properties don't exist.

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);
{ a: { b: { foo: 'test1' }, c: { test2: 'bar' } } }

Creating a Custom setUpdateProp Function

You can implement your own recursive function to safely set nested properties without external dependencies:

const setUpdateProp = (object, path, value) => {
    if (path.length === 1) object[path[0]] = value;
    else if (path.length === 0) throw new Error("Path cannot be empty");
    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);
        }
    }
};

Example: Using Custom Function

const setUpdateProp = (object, path, value) => {
    if (path.length === 1) object[path[0]] = value;
    else if (path.length === 0) throw new Error("Path cannot be empty");
    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);
        }
    }
};

var obj = {
    level1:{
        level2:{
            level3:{
                name: "Foo"
            }
        },
        anotherLevel2: "bar"
    }
};

setUpdateProp(obj, ["level1", "level2"], "FooBar");
console.log(obj);
{ level1: { level2: 'FooBar', anotherLevel2: 'bar' } }

Comparison

Method Dependencies Path Format Use Case
Lodash set() Requires lodash Dot notation string Production apps with lodash
Custom function None Array of keys Lightweight solutions

Conclusion

For production applications already using Lodash, _.set() is the preferred choice. For lightweight solutions or avoiding dependencies, a custom recursive function works effectively for safely setting nested object properties.

Updated on: 2026-03-15T23:18:59+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements