Search code examples
javascriptarraysobject

javascript update json value by list of keys


I have an object which goes so deep. For example:

section: {
     data: {
          x = 4
     }
}

Real one is even more deep.

How can I update the x value when I have such a function:

const keys = [section, data, x];
const update = (newValue, keys) => {
      // it should be like this
      // myObjc[section][data][x] = newValue;
}

Solution

  • enter image description here

    I think what you need is a deep set value function, like this

    const update = (newValue, keys, obj) => {
        for(const key of keys.slice(0,-1))
            obj=obj[key];
        obj[keys[keys.length-1]]=newValue
    }