Skip to content

How can i access and change a value in an object with an array of keys

const object = {
    key1: 'example_key1',
    key2: {
        key3: 'example_key2'

const string = 'key1'
const array = ['key2', 'key3']

object[string] = 'foo' // Work
object[array] = 'bar' // Dont work

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.



You need to do something like the following:

function set(obj, path, value) {
  var schema = obj
  var len = path.length
  for(var i = 0; i < len - 1; i++) {
    var elem = path[i]
    if (!schema[elem] ) schema[elem] = {}
    schema = schema[elem]

  schema[path[len-1]] = value

And then you could use it in the following way:

set(object, array, 'someText')

With a function like the above set you can update an object passing an array of nested keys and the new value.

User contributions licensed under: CC BY-SA
4 People found this is helpful