将数组中有相同的key合并为新的数组,其实也就是将一维数组修改为多维数组:

let data = [
  { name: "苹果", orderCode: "AAAAAAAA" },
  { name:
"橘子", orderCode: "BBBBBBBB" },
  { name:
"香蕉", orderCode: "CCCCCCCCC" },   { name: "苹果", orderCode: "DDDDDDDD" },   { name: "橘子", orderCode: "EEEEEEE" },   { name: "苹果", orderCode: "FFFFFFF" }, ];

想要修改为:

const newAr = [
  {
    name: "苹果",
    goodsList: [
          { name: "苹果", orderCode: "AAAAAAAA" },
          { name: "苹果", orderCode: "DDDDDDDD" },
          { name: "苹果", orderCode: "FFFFFFF" },
        ],
      },
  {
    name: "橘子",
    goodsList: [{ name: "橘子", orderCode: "BBBBBBBB" }],
  },
  {
    name: "香蕉",
    goodsList: [{ name: "香蕉", orderCode: "CCCCCCCCC" }],
  },
];

代码:

方法一:

let tempList = [];
    let resultList = [];
    data.map((item) => {
      if (tempList.indexOf(item.name) === -1) {
        tempList.push(item.name);
        resultList.push({
          name: item.name,
          goodsList: [],
        });
      }
    });

    resultList.map((item) => {
      data.map((items) => {
        if (item.name === items.name) {
          item.goodsList.push(items);
        }
      });
});

方法二:

let tempArr = [];
    let afterData = [];
    for (let i = 0; i < data.length; i++) {
      if (tempArr.indexOf(data[i].name) === -1) {
        afterData.push({
          name: data[i].name,
          origin: [data[i]],
        });
        tempArr.push(data[i].name);
      } else {
        for (let j = 0; j < afterData.length; j++) {
          if (afterData[j].name == data[i].name) {
            afterData[j].origin.push(data[i]);
            break;
          }
        }
      }
}

 

posted on 2021-05-18 15:14  liumcb  阅读(1886)  评论(0编辑  收藏  举报