互联网技术 · 2024年2月15日

JavaScript合并多个对象并去重

方法一:

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}

OpenMagic API

Need more than content? Move into the product flow.

If you are here for model access, pricing, developer docs, or the future API console, the dedicated product path now lives on api.openmagic.ai.