0

I want to update an attribute of an object but the attribute is not known before hand and is rather stored in a variable.
I have an object "obj" like below

 var obj={ a : 1, b : 2 }

if I want to change attribute "a" to 3 then I can just do obj.a = 3 but I have a variable "attribute_to_change" which has the attribute that I want to change. I want to be able to somehow use the variable value to change the respective object attribute.
Something like below

obj.attribute_to_change = 3

Currently I have to write a separate line code of for each type of attribute that I want to change. But I can actually just make one function and pass the value and the attribute to be changed if I figure this out.

ffs
  • 97
  • 2
  • 8
  • 1
    `obj[attribute_to_change] = 3` – Nicholas Tower Sep 07 '20 at 11:51
  • Do you mean something like this? `const updateObject = (obj, key, newValue) => ({ ...obj, [key]: newValue })` which you can then invoke like so: `updateObject(myObject, 'attributeToChange', 3)` – nbokmans Sep 07 '20 at 11:51

0 Answers0