数组对象根据某个对象合并

    let arr = [
      { id: 1, list: { name: 999} },
      { id: 1, list: { name: 888} },
      { id: 2, list: { name: 777} },
      { id: 2, list: { name: 666} },
      { id: 3, list: { name: 555} },
      { id: 3, list: { name: 444 } },
    ];

    let Arr1 = [],
      Arr2 = [];
    for (let i = 0; i < arr.length; i++) {
      if (Arr1.indexOf(arr[i].id) === -1) {
        Arr2.push({
          id: arr[i].id,
          list: [arr[i].list],
        });
        Arr1.push(arr[i].id);
      } else {
        for (let j = 0; j < Arr2.length; j++) {
          if (Arr2[j].id == arr[i].id) {
            Arr2[j].list.push(arr[i].list);
          }
        }
      }
    }
    console.log(Arr2);
    Arr2=[{  id: 1,list: [{name: 999},{name: 888}]},{  id: 2,list: [{name: 777},{name: 666}]..............}
]

 

posted @ 2023-01-17 17:45  front-gl  阅读(29)  评论(0编辑  收藏  举报