JS 根据数组对象的属性拆分成多个数组

在开发渲染多个echarts图表时,需要将数组根据属性分组成多个数组,以下是实际的数组处理
 

let BaseLineAndLessonLearnByGroupList= [
        {
          name: 'BaseLine',
          value: 1,
          DeptName: 'Logisti',
        },
        {
          name: 'LessonLearn',
          value: 1,
          DeptName: 'Logisti',
        },
        {
          name: 'BaseLine',
          value: 1,
          DeptName: 'ME',
        },
        {
          name: 'LessonLearn',
          value: 1,
          DeptName: 'ME',
        },
      ],

以上是部门数据数组,需要根据部门名称分组生成多个数组

        let dataArr = []
        this.BaseLineAndLessonLearnList.map((mapItem) => {
          if (dataArr.length == 0) {
            dataArr.push({ DeptName: mapItem.DeptName, List: [mapItem] })
          } else {
            let res = dataArr.some((item) => {
              //判断相同的部门,有就添加到当前项
              if (item.DeptName == mapItem.DeptName) {
                item.List.push(mapItem)
                return true
              }
            })
            if (!res) {
              //如果没找相同的部门添加一个新对象
              dataArr.push({ DeptName: mapItem.DeptName, List: [mapItem] })
            }
          }
        })
        let BaseLineAndLessonLearnByGroupList = dataArr

以下是最终生成的数组

let BaseLineAndLessonLearnByGroupList =[
          {
            DeptName: 'ME',
            List: [
              {
                name: 'BaseLine',
                value: 1,
                DeptName: 'ME',
              },
              {
                name: 'LessonLearn',
                value: 1,
                DeptName: 'ME',
              },
            ],
          },
          {
            DeptName: 'Logisti',
            List: [
              {
                name: 'BaseLine',
                value: 1,
                DeptName: 'Logisti',
              },
              {
                name: 'LessonLearn',
                value: 1,
                DeptName: 'Logisti',
              },
            ],
          },
        ]
 

你可能感兴趣的:(JS 根据数组对象的属性拆分成多个数组)