For example, if I have a string:
var foo = 'a.b.c';
... and Object:
var bar = {
a: {
b: {
c: null
}
}
}
How can I use the string to set the value of 'c' to 'Hello World!"?
For example, if I have a string:
var foo = 'a.b.c';
... and Object:
var bar = {
a: {
b: {
c: null
}
}
}
How can I use the string to set the value of 'c' to 'Hello World!"?
Here's one of those not so simple or consistent ways
var bar = {
a: {
b: {
c: 'test'
}
}
}
var foo = 'a.b.c',
arr = foo.split('.'),
o = bar;
arr.forEach(function(key, i) {
if (i === arr.length-1) {
o[key] = 'Hello World'
}else{
o = o[key];
}
});
FIDDLE
Another possible solution is to use eval, but it is unsafe and mostly discouraged:
var foo = "a.b.c";
var bar = {
a: {
b: {
c: null
}
}
}
eval("bar." + foo + " = 'Hello World'; ");
alert(bar.a.b.c);
FIDDLE
Another example with a small function (DEMO):
function setVal(obj, accessors, val) {
var parts = accessors.split('.');
for(var i = 0; i < parts.length-1; i++) {
obj = obj[parts[i]]
}
obj[parts[parts.length-1]] = val;
}
setVal(bar, foo, 'Hello World');
Also to get the value:
function getVal(obj, accessors) {
var parts = accessors.split('.');
for(var i = 0; i < parts.length; i++) {
obj = obj[parts[i]]
}
return obj;
}
var val = getVal(bar, foo);