0

I'm fairly new to Javascript Object. I've defined a non-destructive function to update an object like this:

function updateObjectWithKeyAndValue(object, key, value) {
  return Object.assign({}, object, { key: value }); 
}

let object = {a: 1};
console.log(updateObjectWithKeyAndValue(object, 'b', 2));
console.log(object);

I'm getting the return value of the function as { a: 1, key: 2 } instead of { a: 1, b: 2 }. Is there something I'm not doing right? Thanks...

Jelil
  • 1
  • 1
  • What about `object[key] = value;`? – D. Pardal Oct 08 '20 at 21:57
  • D. Pardal, because I don't want to modify this same ```object```. I only want the function to return the items in the ```object``` variable plus the new key/value pair passed as arguments to the function – Jelil Oct 09 '20 at 20:37

1 Answers1

1

{ key: value } is an object with a property named “key”. To name the property according to the value in the variable key, use a computed property name:

{ [key]: value }

If your JavaScript environment supports object spread, the whole thing can be written as:

return { ...object, [key]: value };
Ry-
  • 218,210
  • 55
  • 464
  • 476