Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically set property of nested object

I have an object that could be any number of levels deep and could have any existing properties. For example:

var obj = {     db: {         mongodb: {             host: 'localhost'         }     } }; 

On that I would like to set (or overwrite) properties like so:

set('db.mongodb.user', 'root'); // or: set('foo.bar', 'baz'); 

Where the property string can have any depth, and the value can be any type/thing.
Objects and arrays as values don't need to be merged, should the property key already exist.

Previous example would produce following object:

var obj = {     db: {         mongodb: {             host: 'localhost',             user: 'root'         }     },     foo: {         bar: baz     } }; 

How can I realize such a function?

like image 949
John B. Avatar asked Sep 21 '13 19:09

John B.


People also ask

How do you create an object that is nested inside another object?

const obj = { code: "AA", sub: { code: "BB", sub: { code: "CC", sub: { code: "DD", sub: { code: "EE", sub: {} } } } } }; Notice that for each unique couple in the string we have a new sub object and the code property at any level represents a specific couple.

How do I update nested objects?

To update nested properties in a state object in React: Pass a function to setState to get access to the current state object. Use the spread syntax (...) to create a shallow copy of the object and the nested properties. Override the properties you need to update.

What is nested object in JavaScript?

Nested objects are objects that are inside another object. You can create nested objects within a nested object. In the following example, Salary is an object that resides inside the main object named Employee . The dot notation can access the property of nested objects. JavaScript.

How do you add a property to an object?

One way is to add a property using the dot notation: obj. foo = 1; We added the foo property to the obj object above with value 1.


2 Answers

This function, using the arguments you specified, should add/update the data in the obj container. Note that you need to keep track of which elements in obj schema are containers and which are values (strings, ints, etc.) otherwise you will start throwing exceptions.

obj = {};  // global object  function set(path, value) {     var schema = obj;  // a moving reference to internal objects within obj     var pList = path.split('.');     var len = pList.length;     for(var i = 0; i < len-1; i++) {         var elem = pList[i];         if( !schema[elem] ) schema[elem] = {}         schema = schema[elem];     }      schema[pList[len-1]] = value; }  set('mongo.db.user', 'root'); 
like image 188
bpmason1 Avatar answered Sep 26 '22 13:09

bpmason1


Lodash has a _.set() method.

_.set(obj, 'db.mongodb.user', 'root'); _.set(obj, 'foo.bar', 'baz'); 
like image 32
aheuermann Avatar answered Sep 26 '22 13:09

aheuermann