• 當(dāng)前位置:首頁 >  站長 >  編程技術(shù) >  正文

    js合并多個對象并且去重

     2020-11-05 15:30  來源: 田珊珊個人博客   我來投稿 撤稿糾錯

      阿里云優(yōu)惠券 先領(lǐng)券再下單

    方法一:

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

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

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

    如果有重復(fù)的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)的所有可枚舉屬性,復(fù)制到目標(biāo)對象(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方法的第一個參數(shù)是目標(biāo)對象,后面的參數(shù)都是源對象。

    注意,如果目標(biāo)對象與源對象有同名屬性,或多個源對象有同名屬性,則后面的屬性會覆蓋前面的屬性。

    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

    申請創(chuàng)業(yè)報道,分享創(chuàng)業(yè)好點子。點擊此處,共同探討創(chuàng)業(yè)新機遇!

    相關(guān)文章

    熱門排行

    信息推薦