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

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

    Simply adding properties:

    And we want to add prop2 : 2 to this object, these are the most convenient options:

    1. Dot operator: object.prop2 = 2;
    2. square brackets: object['prop2'] = 2;

    So which one do we use then?

    The dot operator is more clean syntax and should be used as a default (imo). However, the dot operator is not capable of adding dynamic keys to an object, which can be very useful in some cases. Here is an example:

    const obj = {
      prop1: 1
    }
    
    const key = Math.random() > 0.5 ? 'key1' : 'key2';
    
    obj[key] = 'this value has a dynamic key';
    
    console.log(obj);

    Merging objects:

    When we want to merge the properties of 2 objects these are the most convenient options:

    1. Object.assign(), takes a target object as an argument, and one or more source objects and will merge them together. For example:

    const object1 = {
      a: 1,
      b: 2,
    };
    
    const object2 = Object.assign({
      c: 3,
      d: 4
    }, object1);
    
    console.log(object2);

    1. Object spread operator ...

    const obj = {
      prop1: 1,
      prop2: 2
    }
    
    const newObj = {
      ...obj,
      prop3: 3,
      prop4: 4
    }
    
    console.log(newObj);

    Which one do we use?

    • The spread syntax is less verbose and has should be used as a default imo. Don't forgot to transpile this syntax to syntax which is supported by all browsers because it is relatively new.
    • Object.assign() is more dynamic because we have access to all objects which are passed in as arguments and can manipulate them before they get assigned to the new Object.

提交回复
热议问题