JavaScript
x
13
13
1
const object = {
2
key1: 'example_key1',
3
key2: {
4
key3: 'example_key2'
5
}
6
}
7
8
const string = 'key1'
9
const array = ['key2', 'key3']
10
11
object[string] = 'foo' // Work
12
object[array] = 'bar' // Dont work
13
How can I access and change the object with the array of keys?
I have tried loadash.get
but it can only get values not change them.
Advertisement
Answer
You need to do something like the following:
JavaScript
1
12
12
1
function set(obj, path, value) {
2
var schema = obj
3
var len = path.length
4
for(var i = 0; i < len - 1; i++) {
5
var elem = path[i]
6
if (!schema[elem] ) schema[elem] = {}
7
schema = schema[elem]
8
}
9
10
schema[path[len-1]] = value
11
}
12
And then you could use it in the following way:
JavaScript
1
2
1
set(object, array, 'someText')
2
With a function like the above set
you can update an object passing an array of nested keys and the new value.