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

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

    You can create a new object by using the {[key]: value} syntax:

    const foo = {
      a: 'key',
      b: 'value'
    }
    
    const bar = {
      [foo.a]: foo.b
    }
    
    console.log(bar); // {key: 'value'}
    console.log(bar.key); // value
    
    const baz = {
      ['key2']: 'value2'
    }
    
    console.log(baz); // {key2: 'value2'}
    console.log(baz.key2); // value2

    With the previous syntax you can now use the spread syntax {...foo, ...bar} to add a new object without mutating your old value:

    const foo = {a: 1, b: 2};
    
    const bar = {...foo, ...{['c']: 3}};
    
    console.log(bar); // {a: 1, b: 2, c: 3}
    console.log(bar.c); // 3

    0 讨论(0)
  • 2020-11-21 07:31

    You can either add it this way:

    arr['key3'] = value3;
    

    or this way:

    arr.key3 = value3;
    

    The answers suggesting keying into the object with the variable key3 would only work if the value of key3 was 'key3'.

    0 讨论(0)
  • 2020-11-21 07:31

    In order to prepend a key-value pair to an object so the for in works with that element first do this:

        var nwrow = {'newkey': 'value' };
        for(var column in row){
            nwrow[column] = row[column];
        }
        row = nwrow;
    
    0 讨论(0)
  • 2020-11-21 07:32

    We can do this in this way too.

    var myMap = new Map();
    myMap.set(0, 'my value1');
    myMap.set(1, 'my value2');
     for (var [key, value] of myMap) {
      console.log(key + ' = ' + value);
     }
    
    0 讨论(0)
  • 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!

    0 讨论(0)
  • 2020-11-21 07:34

    In case you have multiple anonymous Object literals inside an Object and want to add another Object containing key/value pairs, do this:

    Firebug' the Object:

    console.log(Comicbook);
    

    returns:

    [Object { name="Spiderman", value="11"}, Object { name="Marsipulami", value="18"}, Object { name="Garfield", value="2"}]

    Code:

    if (typeof Comicbook[3]=='undefined') {
        private_formArray[3] = new Object();
        private_formArray[3]["name"] = "Peanuts";
        private_formArray[3]["value"] = "12";
    }
    

    will add Object {name="Peanuts", value="12"} to the Comicbook Object

    0 讨论(0)
提交回复
热议问题