通过 Object.assign{...obj1, ...obj2} 实现拷贝对象,合并对象属性时需要注意的问题

    科技2023-11-17  82

    当 多个源对象含有相同的属性名时,后面的源对象的属性值会覆盖前面的

    比如:

    let a = { test: 'aa' };  let b = { test: 'cc' };  let c = {...a, ...b}; 或者 let d = {}; Object.assign(d, a, b); console.log('c', c); // {test: 'cc'} console.log('d', d); // {test: 'cc'}

    所以,需要注意的是:当多个源对象的相同的属性名的属性值是都是对象的话,操作的结果并不是对象的属性的合并而是后面的属性值覆盖了前面的。

    比如:

    let t1 = {label: {text: 't1'}}; let t2 = {label: {positon: 'right'}}; let t3 = {...t1, ...t2}; //t3 --> {label: {positon: 'right'}}

     

    Processed: 0.019, SQL: 8