test

66 阅读1分钟

    var arr = [{
      aname: ['1'],
      child: [
        { noon: 's' },
        { noon: 'x' }
      ]
    }, {
      aname: ['2'],
      child: [
        { noon: 'x' },
        { noon: 'w' }
      ]
    }, {
      aname: ['3'],
      child: [
        { noon: 's' },
        { noon: 'x' },
        { noon: 'w' },
        { noon: 'l' }
      ]
    }, {
      aname: ['4'],
      child: [
        { noon: 's' },
        { noon: 'x' },
        { noon: 'w' },
        { noon: 'l' }
      ]
    }]

    arr.forEach((a, ai) => {
      arr.forEach((b, bi) => {
        // 如果非对称项目
        if (ai < bi) {
          // 元数组
          a.child.forEach((noon, i) => {
            // 元数组 与 对照数组中的 child含有 交叉值
            const hasNoon = b.child.find(no => no.noon === noon.noon)
            // 含有相同项
            if (hasNoon) {
              // 对照项 child 的值需要删除
              arr[bi].child[i].go = true;
              // 元数组追加name属性
              a.aname = [...a.aname, ...b.aname]
            }
          })
        }
        // 元数组 最后一项 与 对照组非最后一项
        else if ((ai === arr.length - 1) && ai !== bi) {
          // 循环 元数组 最后一项 child的值
          arr[ai].child.forEach(end => {
            // 与 对照组含有交叉值
            if(arr[bi].child.find(who => who.noon === end.noon)) {
              // 元数组 最后一项 child的值需要删掉
              end.go = true;
            }
          })
        }
      })
    });

    arr.forEach(el => {
      // aname 去重
      el.aname =  [...new Set(el.aname)]
      // child删除重复项
      el.child = el.child.filter(who => !who.go)
    })

    arr = arr.filter(who => who.child.length)

    console.log(arr);

优化

var arr = [
  {
    aname: ['1'],
    child: [
      { noon: 's' },
      { noon: 'x' }
    ]
  },
  {
    aname: ['2'],
    child: [
      { noon: 'x' },
      { noon: 'w' }
    ]
  },
  {
    aname: ['3'],
    child: [
      { noon: 's' },
      { noon: 'x' },
      { noon: 'w' },
      { noon: 'l' }
    ]
  },
  {
    aname: ['4'],
    child: [
      { noon: 's' },
      { noon: 'x' },
      { noon: 'w' },
      { noon: 'l' }
    ]
  }
];

// 创建一个 Map 用于存储已经出现过的 child 对象
const childMap = new Map();

arr.forEach(item => {
  // 去除重复的 child 对象
  item.child = item.child.filter(child => {
    const key = JSON.stringify(child);
    if (childMap.has(key)) {
      return false; // 如果已存在,则过滤掉
    }
    childMap.set(key, true); // 否则加入 Map 中
    return true;
  });

  // 合并重复的 aname
  arr.forEach(other => {
    if (other !== item) {
      item.child.forEach(child => {
        if (other.child.some(c => c.noon === child.noon)) {
          item.aname = [...new Set([...item.aname, ...other.aname])];
        }
      });
    }
  });
});

// 过滤掉 child 长度为 0 的对象
arr = arr.filter(item => item.child.length > 0);

console.log(arr);