How to interpolate a key based on a parameter and update its value in an object es6

I have

const abc = {
  main: {
    primary: 'initialPrimary',
    },
  buttons: {
    text: 'initialText',
  },
}
const updateAbc = (node, key, value) => {
return {updated abc}
}

So, if I call updateAbc('main','primary','updatedPrimary'), it should return updated abc object

{
  main: {
    primary: 'updatedPrimary',
   },
  buttons: {
    text: 'initialText',
  },
}

or when called updateAbc('buttons','text','updatedText'), it should return updated abc object with values

{
  main: {
    primary: 'initialPrimary',
  },
  buttons: {
    text: 'updatedText',
  },
}

It should update only for the value passed. How can it be done in es6?

Answer

const abc = {
  main: {
    primary: 'initialPrimary',
    },
  buttons: {
    text: 'initialText',
  },
}

const updateAbc = (node, key, value) => {
  return {
     ...abc, 
    [node]: {
      [key]: value
    } 
  }
}

Note that this won’t check for non-existent nodes or keys as-is.

You asked specifically for es6, so that’s what I answered with. This works by spreading abc and then dynamically using node and key to provide the path to the updated value.

By using Object.assign you could achieve the same result by doing:

const updateAbc = (node, key, value) => {
  var copyAbc = Object.assign({},abc)
  copyAbc[node][key] = value
  return copyAbc
}

But that will fail and produce an error if given a non-existent node name