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

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

提交回复
热议问题