JavaScript merging objects by id

前端 未结 16 1902
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 09:43

What\'s the correct way to merge two arrays in Javascript?

I\'ve got two arrays (for example):

var a1 = [{ id : 1, name : \"test\"}, { id : 2, name :         


        
16条回答
  •  执笔经年
    2020-11-22 10:42

    A working TypeScript version:

    export default class Merge {
      static byKey(a1: any[], a2: any[], key: string) {
        const res = a1.concat(a2).reduce((acc, x) => {
          acc[x[key]] = Object.assign(acc[x[key]] || {}, x);
          return acc;
        }, {});
    
        return Object.entries(res).map(pair => {
          const [, value] = pair;
          return value;
        });
      }
    }
    
    test("Merge", async () => {
      const a1 = [{ id: "1", value: "1" }, { id: "2", value: "2" }];
      const a2 = [{ id: "2", value: "3" }];
    
      expect(Merge.byKey(a1, a2, "id")).toStrictEqual([
        {
          id: "1",
          value: "1"
        },
        { id: "2", value: "3" }
      ]);
    });
    
    

提交回复
热议问题