Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a nested object value [duplicate]

Tags:

javascript

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.

like image 673
Kenny Thompson Avatar asked Dec 15 '22 22:12

Kenny Thompson


1 Answers

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

like image 124
Raul Garcia Avatar answered Dec 29 '22 15:12

Raul Garcia