js数组通过多个字段进行递归分组

556 阅读1分钟

数据结构:

let list = [
    { year: '2021', month: '03', name: 'asjdl' },
    { year: '2021', month: '03', name: 'asdf' },
    { year: '2021', month: '04', name: 'asjggadl' },
    { year: '2021', month: '04', name: 'hdfg' },
    { year: '2020', month: '03', name: 'etyw' },
    { year: '2020', month: '03', name: 'urerb' },
    { year: '2020', month: '06', name: 'ewryh' },
    { year: '2020', month: '06', name: 'fuie' }
]

需求是要通过year和month两个字段进行递归分组

转换后的数据结构:

[
  {
    "year": "2021",
    "list": [
      {
        "month": "03",
        "list": [
          { "year": "2021", "month": "03", "name": "asjdl" },
          { "year": "2021", "month": "03", "name": "asdf" }
        ]
      },
      {
        "month": "04",
        "list": [
          { "year": "2021", "month": "04",  "name": "asjggadl" },
          { "year": "2021", "month": "04", "name": "hdfg" }
        ]
      }
    ]
  },
  ...
]

通过递归的方式对原数组进行处理

方法如下

function recursiveGrouping(array, keys = ['year', 'month'], index = 0) {
      let temp = []
      if (keys[index]) {
        array.forEach((item) => {
          let data = temp.find((x) => x[keys[index]] == item[keys[index]])

          if (data) {
            data.list.push(item)
          } else {
            temp.push({
              [keys[index]]: item[keys[index]],
              list: [item],
            })
          }
        })
        index++
        temp.forEach((item) => {
          item.list = this.recursiveGrouping(item.list, keys, index)
        })
      } else {
        return array
      }
      return temp
    }