user3130985 user3130985 - 4 months ago 8
Javascript Question

Access Javascript Object with changing values

If I have a JSON, for example:

{
"test1":{
"test11":"someting",
"test12":"something else"
},
"test2":{
"test21":"asdasd",
"test22":"qwasd"
}
}


I want to access and modify some data but i don't know which one.
I'll have an array of keys like this:

["test2","test22"]
and a value:
"change to this"
.

I want to change the
myjson.test2.test22
data to
"change to this"
.

Is there some simple and elegant way to do this?

Note that I don't know what the array's content will be, so I cant use the
myjson.test2.test22
access method.

Answer

You could use Array#reduce and walk the path. Then assign the value to the object with the last key.

var object = { "test1": { "test11": "someting", "test12": "something else" }, "test2": { "test21": "asdasd", "test22": "qwasd" } },
    path = ["test2", "test22"],
    lastKey = path.pop();

path.reduce(function (o, k) {
    return o[k];
}, object)[lastKey] = 'change to this';

console.log(object);

For unknow properties, i suggets to make a check befor and use a default object then.

var object = { "test1": { "test11": "someting", "test12": "something else" }, "test2": { "test21": "asdasd", "test22": "qwasd" } },
    path = ["test2", "test22", "42"],
    lastKey = path.pop();

path.reduce(function (o, k) {
    (o[k] !== null && typeof o[k] === 'object') || (o[k] = {});
    return o[k];
}, object)[lastKey] = 'change to this';

console.log(object);