js----数组对象中根据某个相同的属性值合并其他项

    let arr = [
      { id: 1, list: { id: 66 } },
      { id: 1, list: { id: 44 } },
      { id: 2, list: { id: 55 } },
      { id: 2, list: { id: 33 } },
      { id: 3, list: { id: 11 } },
      { id: 3, list: { id: 22 } }
    ]

    let tempArr = [], newArr = []
    for (let i = 0; i < arr.length; i++) {
      if (tempArr.indexOf(arr[i].id) === -1) {
        newArr.push({
          id: arr[i].id,
          list: [arr[i].list]
        })
        tempArr.push(arr[i].id);
      } else {
        for (let j = 0; j < newArr.length; j++) {
          if (newArr[j].id == arr[i].id) {
            newArr[j].list.push(arr[i].list)
          }
        }
      }
    }

    console.log(newArr)

 

场景:

    getTableData() {
      this.$observer.$on("selectedProject", data => {
        let list = [];
        data.forEach(item => {
          if (item.select === 1) list.push(item);
        });
        this.tableData = list;
        console.log(data, this.tableData);
        this.tableData.forEach(item => {
          item.arr = this.merger(item.lisVos);
      // 根据reportTime排序 item.arr.sort(
function(a, b) { if (a.reportTime < b.reportTime) { return -1; } else if (a.reportTime == b.reportTime) { return 0; } else { return 1; } }); let str = ""; item.arr.forEach(ele => { str += ele.details + ";" + "\n"; }); item.details = str; }); }); }, // 传入一个数组,将reportTime相同的对象中的name合并到details中 merger(arr) { let tempArr = [], newArr = []; for (let i = 0; i < arr.length; i++) { if (tempArr.indexOf(arr[i].reportTime) === -1) { newArr.push({ reportTime: arr[i].reportTime, name: [arr[i].name] }); tempArr.push(arr[i].reportTime); } else { for (let j = 0; j < newArr.length; j++) { if (newArr[j].reportTime == arr[i].reportTime) { newArr[j].name.push(arr[i].name) } } } }
    // 给newArr添加一个新字段details newArr.forEach(item
=> { item.details = item.reportTime + ":" + item.name }) return newArr; }

 

 

posted @ 2020-06-18 14:41  吴小明-  阅读(8698)  评论(0编辑  收藏  举报