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?
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.
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.
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.
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.
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');
Lodash has a _.set() method.
_.set(obj, 'db.mongodb.user', 'root'); _.set(obj, 'foo.bar', 'baz');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With