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

前端 未结 24 3323
情歌与酒
情歌与酒 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:33

    Year 2017 answer: Object.assign()

    Object.assign(dest, src1, src2, ...) merges objects.

    It overwrites dest with properties and values of (however many) source objects, then returns dest.

    The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

    Live example

    var obj = {key1: "value1", key2: "value2"};
    Object.assign(obj, {key3: "value3"});
    
    document.body.innerHTML = JSON.stringify(obj);

    Year 2018 answer: object spread operator {...}

    obj = {...obj, ...pair};
    

    From MDN:

    It copies own enumerable properties from a provided object onto a new object.

    Shallow-cloning (excluding prototype) or merging of objects is now possible using a shorter syntax than Object.assign().

    Note that Object.assign() triggers setters whereas spread syntax doesn’t.

    Live example

    It works in current Chrome and current Firefox. They say it doesn’t work in current Edge.

    var obj = {key1: "value1", key2: "value2"};
    var pair = {key3: "value3"};
    obj = {...obj, ...pair};
    
    document.body.innerHTML = JSON.stringify(obj);

    Year 2019 answer

    Object assignment operator +=:

    obj += {key3: "value3"};
    

    Oops... I got carried away. Smuggling information from the future is illegal. Duly obscured!

提交回复
热议问题