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?
set('foo', 'bar'); set('foo.baz', 'qux');
, wherefoo
first holds aString
then becomes anObject
? What happens to'bar'
?set()
method and just doobj.db.mongodb.user = 'root';
you'd have exactly what you seem to be wanting ?