How can I add a key/value pair to a JavaScript object?

前端 未结 24 3325
情歌与酒
情歌与酒 2020-11-21 07:01

Here is my object literal:

var obj = {key1: value1, key2: value2};

How can I add field key3 with value3 to the ob

24条回答
  •  醉话见心
    2020-11-21 07:41

    A short and elegant way in next Javascript specification (candidate stage 3) is:

    obj = { ... obj, ... { key3 : value3 } }

    A deeper discussion can be found in Object spread vs Object.assign and on Dr. Axel Rauschmayers site.

    It works already in node.js since release 8.6.0.

    Vivaldi, Chrome, Opera, and Firefox in up to date releases know this feature also, but Mirosoft don't until today, neither in Internet Explorer nor in Edge.

提交回复
热议问题