The lodash method _.set exported as a module for setting values at deep object paths with automatic intermediate object creation.
npx @tessl/cli install tessl/npm-lodash-set@4.3.0The lodash method _.set exported as a standalone Node.js module for setting values at deep object paths with automatic intermediate object creation. This package allows developers to safely set nested properties using string or array notation without worrying about missing intermediate objects or arrays.
npm install lodash.setvar set = require('lodash.set');For ES6 modules (via transpilation or bundler):
import set from 'lodash.set';var set = require('lodash.set');
// Create an object to modify
var object = { 'a': [{ 'b': { 'c': 3 } }] };
// Set a nested value using dot notation
set(object, 'a[0].b.c', 4);
console.log(object.a[0].b.c);
// => 4
// Set values in missing paths - creates intermediate objects/arrays automatically
set(object, ['x', '0', 'y', 'z'], 5);
console.log(object.x[0].y.z);
// => 5
// Works with dot notation strings
set(object, 'deep.nested.property', 'hello');
console.log(object.deep.nested.property);
// => 'hello'Sets the value at path of object. If a portion of path doesn't exist, it's created. Arrays are created for missing index properties while objects are created for all other missing properties.
Note: This method mutates object.
/**
* Sets the value at `path` of `object`. If a portion of `path` doesn't exist,
* it's created. Arrays are created for missing index properties while objects
* are created for all other missing properties.
*
* @param {Object} object - The object to modify
* @param {Array|string} path - The path of the property to set
* @param {*} value - The value to set
* @returns {Object} Returns `object`
*/
function set(object, path, value);Object): The object to modify. If null or undefined, returns the object unchanged.Array|string): The path of the property to set. Can be:
'a.b.c''a[0].b.c' or 'a["key"].b''a[0].b.c.d'['a', '0', 'b', 'c']*): The value to set at the specified path.Objectobject. The original object is mutated.'a.b.c' creates nested objects)'a[0].b' creates array at a)Basic path setting:
var obj = {};
set(obj, 'user.name', 'John');
// obj becomes: { user: { name: 'John' } }Array index creation:
var obj = {};
set(obj, 'items[0].id', 123);
// obj becomes: { items: [{ id: 123 }] }Complex nested structures:
var obj = {};
set(obj, 'users[0].profile.settings.theme', 'dark');
// obj becomes: { users: [{ profile: { settings: { theme: 'dark' } } }] }Using array path notation:
var obj = {};
set(obj, ['data', 'results', '0', 'value'], 42);
// obj becomes: { data: { results: [{ value: 42 }] } }Handling null/undefined objects:
set(null, 'a.b.c', 123);
// => null (no operation performed)
set(undefined, 'a.b.c', 123);
// => undefined (no operation performed)