星星博客 »  > 

js数组对象按种类分组

传入数组

     let arr = [
     { year: 2021 }, 
     { year: 2020 },
     { year: 2020 },
     { year: 2019 },
     { year: 2021 }]
     let arrList = this.sort_pro(arr, ['year'])
     console.log(arrList)

结果
在这里插入图片描述

调用方法

    sort_pro(data, keys = []) {
      //keys可以传一个数组
      var c = []
      var d = {}
      for (var element of data) {
        let element_keyStr = ''
        let element_key = []
        let element_keyObj = {}
        for (var key of keys) {
          element_key.push(element[key])
          element_keyObj[key] = element[key]
        }
        element_keyStr = element_key.join('_')
        if (!d[element_keyStr]) {
          c.push({
            ...element_keyObj,
            children: [element]
          })
          d[element_keyStr] = element
        } else {
          for (var ele of c) {
            let isTrue = keys.some(key => {
              return ele[key] != element[key]
            })
            if (!isTrue) {
              ele.children.push(element)
            }
          }
        }
      }
      return c
    },

相关文章