I have the following object:
var object = {
"property1": "value1",
"property2": "value2",
"subobject": {
"property1": "value1",
"property2": "value2",
"subobject": {
"property1": "value1",
"property2": "value2",
"subobject": {...
}
}
}
}
I am trying to set one of the nested subobject properties, but the nested level is dynamic.
How can I dynamically set one of these nested properties without doing something like this: object.subobject.subobject = { ... }
?
Edit: So to be more specific, I am trying to set one of the nested subobjects, but I won't know which one each time.
Using recursion - refactor (thanks Rocket Hazmat)
This function works for me!:
/**
* @obj: the json object to change
* @access: string dot separates route to value
* @value: new valu
*/
function setValue(obj,access,value){
if (typeof(access)=='string'){
access = access.split('.');
}
if (access.length > 1){
setValue(obj[access.shift()],access,value);
}else{
obj[access[0]] = value;
}
}
Having an object:
var jsonObject = {
'name' : 'pepe',
'links' :
{
'link1' : 'one',
'link2' : 'two',
'link3' :
{
'link31' : '3url',
'link32' : '3url',
'link33' : '3url'
}
}
}
We can change a value easy with:
setValue(jsonObject,'links.link3.link32','new value!!!');
Thanks
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