This is a reverse question to this question.
Given an object x={a:1,b:2}
and a string c.d=3
, modify object x to the following:
{
a:1,
b:2,
c:{
d:3
}
}
I'm looking for a solution that does not use eval
. The use case is as follows:
x
being a configuration object, we call:
config.set("music.shuffle",true)
Now, music.shuffle
must be parsed somehow and added to the internal object x
inside the config.set function, so that x looks something like:
x={a:1,b:2,music:{shuffle:true}}
Dot notation is one way to access a property of an object. To use dot notation, write the name of the object, followed by a dot (.), followed by the name of the property. Example: var cat = { name: 'Moo', age: 5, }; console.
Dot notation indicates that you're accessing data or behaviors for a particular object type. When you use dot notation, you indicate to Python that you want to either run a particular operation on, or to access a particular property of, an object type.
The dot operator, also known as separator or period used to separate a variable or method from a reference variable. Only static variables or methods can be accessed using class name. Code that is outside the object's class must use an object reference or expression, followed by the dot (.)
To create an object, use the new keyword with Object() constructor, like this: const person = new Object(); Now, to add properties to this object, we have to do something like this: person.
Off the top of my head I guess you can do something like this:
function addValueToObj(obj, newProp) {
newProp = newProp.split("="); // separate the "path" from the "value"
var path = newProp[0].split("."), // separate each step in the "path"
val = newProp.slice(1).join("="); // allow for "=" in "value"
for (var i = 0, tmp = obj; i < path.length - 1; i++) {
tmp = tmp[path[i]] = {}; // loop through each part of the path adding to obj
}
tmp[path[i]] = val; // at the end of the chain add the value in
}
var x = {a:1, b:2};
addValueToObj(x, "c.d=3");
// x is now {"a":1,"b":2,"c":{"d":"3"}}
addValueToObj(x, "e.f.g.h=9=9");
// x is now {"a":1,"b":2,"c":{"d":"3"},"e":{"f":{"g":{"h":"9=9"}}}}
Demo: http://jsfiddle.net/E8dMF/1/
You can do this with lodash.set()
> l=require('lodash') > x={a:1,b:2}; { a: 1, b: 2 } > l.set(x, 'c.d', 3) { a: 1, b: 2, c: { d: 3 } }
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