美文网首页
es6根据某个属性将数组对象进行分组

es6根据某个属性将数组对象进行分组

作者: 哒哒哒哒da | 来源:发表于2022-07-28 11:03 被阅读0次
    // 数组
    export function getGroupArray(list, attr) {
      const map = new Map();
      list.forEach((item, index, arr) => {
        if (!map.has(item[attr])) {
          map.set(
            item[attr],
            arr.filter(a => a[attr] == item[attr])
          );
        }
      });
      return Array.from(map).map(item => [...item[1]]);
    }
    // 对象
    export function getGroupObject(list, attr) {
      const map = new Map();
      list.forEach((item, index, arr) => {
        if (!map.has(item[attr])) {
          map.set(
            item[attr],
            arr.filter(a => a[attr] == item[attr])
          );
        }
      });
      return Object.fromEntries(Array.from(map).map(item => [item[0], item[1]]));
    }
    

    相关文章

      网友评论

          本文标题:es6根据某个属性将数组对象进行分组

          本文链接:https://www.haomeiwen.com/subject/ijtxwrtx.html