js合并多个对象并且去重

来源:田珊珊个人博客 时间:2020-11-05

方法一:

let o1 = { a: 1, b: 2 };

let o2 = { c: 4, d: 5 };

let o3 = {...o1, ...o2};//{ a: 1, b: 2, c: 4, d: 5}

如果有重复的key,则后面的会将前面的值覆盖掉

let o1 = { a: 1, b: 2 };

let o2 = { c: 4, b: 5 };

let o3 = {...o1, ...o2};//{ a: 1, b: 5, c: 4}

方法二:

Object.assign方法用于对象的合并,将源对象(source)的所有可枚举属性,复制到目标对象(target)。

const target = { a: 1 };

const source1 = { b: 2 };

const source2 = { c: 3 };

Object.assign(target, source1, source2);

target // {a:1, b:2, c:3}

Object.assign方法的第一个参数是目标对象,后面的参数都是源对象。

注意,如果目标对象与源对象有同名属性,或多个源对象有同名属性,则后面的属性会覆盖前面的属性。

const target = { a: 1, b: 1 };

const source1 = { b: 2, c: 2 };

const source2 = { c: 3 };

Object.assign(target, source1, source2);

target // {a:1, b:2, c:3}

文章来源:田珊珊个人博客

来源地址:http://www.tianshan277.com/805.html

相关文章

A5创业网 版权所有