Reputation: 975
Suppose I have an object like that.
var t = {
"obj1": {
"obj1.1": "test",
"obj1.2": {
"obj1.1.1": null, // <-- "obj1.1.1" has to have a value.
"obj1.1.2": "test"
}
}
};
And a path to the node where I'd like to add a value, i.e.:
var path = ['obj1', 'obj1.1', 'test'];
How do I add the value programmatically?
Upvotes: 0
Views: 176
Reputation: 121
var tree = {
"obj1": {
"obj1.1": "test",
"obj1.2": {
"obj1.1.1": null,
"obj1.1.2": "test"
}
}
};
var path = ['obj1', 'obj1.1', 'test'];
A static way of setting 'test':
tree[path[0]][path[1]] = path[2];
A static way of replacing 'test' with newObj:
var newObj = { ... };
tree[path[0]][path[1]][path[2]] = newObj;
Upvotes: 0
Reputation: 16468
Supposing this object
var obj = {
"obj1" : {
"obj1.1" : "",
"obj1.2" : {
"obj1.1.1" : "",
"obj1.1.2" : ""
}
}
}
var path = ['obj1', 'obj1.1', 'test'];
the algorithm is:
var el = obj;
for(var i = 0; i < path.length-2; i++) {
el = el[path[i]];
}
el[path[i]] = path[i+1];
or as function
function setpath(obj,path) {
var el = obj;
for(var i = 0; i < path.length-2; i++) {
console.log(i+"="+path[i]);
el = el[path[i]];
}
el[path[i]] = path[i+1];
console.log(el);
}
setpath(obj,['obj1', 'obj1.1', 'test']);
Upvotes: 0
Reputation: 72957
Try this:
function setDeepValue(obj, value, path) {
if(path.length > 1){
var p=path.shift();
if(obj[p]==null || typeof obj[p]!== 'object'){
obj[p] = {};
}
setDeepValue(obj[p], value, path);
}else{
obj[path[0]] = value;
}
}
var obj = {};
var path = ['obj1', 'obj1.1'];
setDeepValue(obj, 'test', path);
console.log(obj); // {"obj1":{"obj1.1":"test"}}
You will however need to fix your object:
var t = {
"obj1": {
"obj1.1": "test",
"obj1.2": {
"obj1.1.1": null, // <-- "obj1.1.1" has to have a value.
"obj1.1.2": "test"
}
}
};
A object can't have a key without a value, so "obj1.1.1"
will have to have a value, even if it's null
.
Upvotes: 1