0

I'm wondering why I'm not able to assign a key / value pair to a given object in JavaScript using some forms of syntax versus others.

function updateObjectWithKeyAndValue(object, key, value) {
  var newPair = {};

  // Why does the syntax below need to be used to create the key / value pair?
  
  newPair[key] = value;

  // Why do "newPair.key = value;" or "newPair = { key: value }" not work?

  var newObject = Object.assign({}, object, newPair);
  return newObject;
}

Thank you for your help!

Louis
  • 1
  • 2
  • 1
    With both methods you are creating another property with literally the name "key". – Wais Kamal Jan 07 '21 at 22:09
  • `object[key] = value` – Mechanic Jan 07 '21 at 22:10
  • Also note that you can simply do `object[key] = value;` instead. –  Jan 07 '21 at 22:10
  • Duplicate: [JavaScript set object key by variable](https://stackoverflow.com/questions/11508463/javascript-set-object-key-by-variable) –  Jan 07 '21 at 22:11
  • `newPair = { [key]: value };` would work, if you want to go nuts. – Heretic Monkey Jan 07 '21 at 22:12
  • `object.key` is equivalent to `object["key"]` – Barmar Jan 07 '21 at 22:14
  • Thank you all for your help. I understand now that `newObject.key` sets the key name to `key` while `newObject[key]` allows for the `key` parameter to be passed properly. I also understand that `object[key] = value;` will achieve the same end result, but I'm trying to preserve the original object and instead return a clone with the new data. – Louis Jan 07 '21 at 22:21

0 Answers0