欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

js对象数组分组

程序员文章站 2022-06-17 19:47:40
...

按照某个字段进行分组

let groupData = [
		{name: "张三",project: "语文",score: "90"},
	    {name: "张三",project: "数学",score: "88"}, 
	    {name: "张三",project: "英语",score: "86"}, 
	    {name: "张三",project: "物理",score: "96"},
	    {name: "李四",project: "语文",score: "92"},
	    {name: "李四",project: "数学",score: "86"}
   	];

    function groupByName(groupData) {
          let result = groupData.reduce((prevValue, currentValue) => {
              let index = -1;
              prevValue.some((item, i) => {
                  if (item.name == currentValue.name) {
                      index = i;
                      return true;
                  }
              })
              if (index > -1) {
                  prevValue[index].projectAndScore.push({
                      project: currentValue.project,
                      score: currentValue.score
                  })
              } else {
                  prevValue.push({
                      name: currentValue.name,
                      projectAndScore: [{
                          project: currentValue.project,
                          score: currentValue.score
                      }]
                  })
              }
              return prevValue;
          }, []);
          console.log(result);
          return result;
      }
      groupByName(groupData);

分组结果如下:

js对象数组分组

相关标签: js