Basic use of Object.assign()

Basic use of Object.assign()

The Object.assign() method is used to copy the values ​​of all enumerable properties from one or more source objects to the target object. It will return the target object.
Object.assign(target, …sources) [target: target object], [souce: source object (multiple)]

1. Example 1 (combined object)

  let object1 = {
    a:1,
    b:2,
    c:3
  };
  
  let object = Object.assign({}, object1,{d:4,e:5});
  
  console.log(object)   //{a: 1, b: 2, c: 3, d: 4, e: 5}

2. Example 2 (Merge objects: if the attributes in the target object have the same key, the attributes will be overwritten by the attributes in the source object. The attributes of the subsequent source objects will similarly override the attributes of the previous source object)

In short: properties in the object will be overwritten when they have the same key

  let object1 = {
    a:1,
    b:2,
    c:3
  };
  let object2 = {
    c:3,
    d:4,
    e:5
  };
  let object = Object.assign({}, object1,object2);
  
  console.log(object)     // {a: 1, b: 2, c: 3, d: 4, e: 5}

3. Example 3 If it is a string, it will be automatically converted to an object, and the others will be ignored, as follows:

const v1 = "abc";
const obj = Object.assign({}, v1); 
console.log(obj);   // { "0": "a", "1": "b", "2": "c" }



const v2 = true;
const v3 = 10;
const v4 = undefined;
const v5 = null;
const obj1 = Object.assign({}, v1,v2,v3,v4); 
console.log(obj1);   // { "0": "a", "1": "b", "2": "c" }

Guess you like

Origin blog.csdn.net/qq_43923146/article/details/109801634