-2

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?

menan
  • 33
  • 1
  • 6
  • Does this answer your question? [How to set object property (of object property of..) given its string name in JavaScript?](https://stackoverflow.com/questions/13719593/how-to-set-object-property-of-object-property-of-given-its-string-name-in-ja) – Heretic Monkey Feb 10 '21 at 16:20

1 Answers1

0
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

jnpdx
  • 45,847
  • 6
  • 64
  • 94