首页 > 解决方案 > 如何根据对象属性对对象数组进行分组?

问题描述

我有一个如下所示的数组:

let data:[
    {
        "class": "X",
        "student":[
            {
                "name": "Bumblebee",
                "id":"SAB77"
            }
        ]
    },
    {
        "class": "X",
        "student":[
            {
                "name": "Omega",
                "id":"SAB78"
            }
        ]
    },
    {
        "class": "IX",
        "student":[
            {
                "name": "Pluto",
                "id":"RBC17"
            }
        ]
    },
    {
        "class": "IX",
        "student":[
            {
                "name":"16 psyche",
                "id":"RBC18"
            }
        ]
    }
]

我想分组如下:


 data:[
    {
        "class": "X",
        "student":[
            {
                "name": "Bumblebee",
                "id":"SAB77"
            },
            {
                "name": "Omega",
                "id":"SAB78"
            }
        ]
    },
    {
        "class": "IX",
        "student":[
            {
                "name": "Pluto",
                "id":"RBC17"
            },
            {
                "name": "16 psyche",
                "id":"RBC18"
            }
        ]
    }
]

标签: javascriptangulartypescript

解决方案


let data = [{
    "class": "X",
    "student": [{
      "name": "Bumblebee",
      "id": "SAB77"
    }]
  },
  {
    "class": "X",
    "student": [{
      "name": "Omega",
      "id": "SAB78"
    }]
  },
  {
    "class": "IX",
    "student": [{
      "name": "Pluto",
      "id": "RBC17"
    }]
  },
  {
    "class": "IX",
    "student": [{
      "name": "16 psyche",
      "id": "RBC18"
    }]
  }
];

const result = data.reduce((acc, obj) => {
  let existedObj = acc.length && acc.find(ele => ele.class === obj.class);
  if (!acc.length || !existedObj) {
    acc.push(obj);
    return acc;
  }
  existedObj.student = [...existedObj.student, ...obj.student];
  return acc;
}, []);

console.log(result);


推荐阅读