对象数组(扁平)转为树形数组

  • Post author:
  • Post category:其他


  let arr = [
    { 'country': '国内', 'reputation': '985', 'university': '北京大学', 'university_id': 'beijig' },
    { 'country': '国内', 'reputation': '211', 'university': '清华大学', 'university_id': 'qinghua' },
    { 'country': '国内', 'reputation': '985', 'university': '浙江大学', 'university_id': 'zhejiang' },
    { 'country': '国内', 'reputation': '211', 'university': '武汉大学', 'university_id': 'wuhan' },
    { 'country': '国内', 'reputation': '其它', 'university': '邯郸大学', 'university_id': 'handan' },
    { 'country': '国内', 'reputation': '其它', 'university': '沧州大学', 'university_id': 'cangzhou' },
    { 'country': '国外', 'reputation': '其它', 'university': '哈弗大学', 'university_id': 'hafu' },
    { 'country': '国外', 'reputation': '其它', 'university': '剑桥大学', 'university_id': 'jianqiao' },
    { 'country': '国外', 'reputation': '其它', 'university': '牛津大学', 'university_id': 'niujin' }
  ]

转为

  let arr1 = [
    {
      country: '国内',
      children: [
        {
          reputation: '985', 
          children: [
            {
              university: '北京大学',
              university_id: 'beijing'
            },
            {
              university: '浙江大学',
              university_id: 'zhejiang'
            }
          ]
        }, 
        {
          reputation: '211', 
          children: [
            {
              university: '清华大学',
              university_id: 'qinghua'
            },
            {
              university: '武汉大学',
              university_id: 'wuhan'
            }
          ]
        }, 
        {
          reputation: '其他', 
          children: [
            {
              university: '邯郸大学',
              university_id: 'handan'
            },
            {
              university: '沧州大学',
              university_id: 'cangzou'
            }
          ]
        }, 
      ]
    }, 
    {
      country: '国外',
      children: [
        {
          reputation: '其他', 
          children: [
            {
              university: '哈弗大学',
              university_id: 'hafu'
            }, 
            {
              university: '剑桥大学',
              university_id: 'jianqiao'
            }, 
            {
              university: '牛津大学',
              university_id: 'niujin'
            }, 
          ]
        }
      ]
    }
  ]

递归分组

// TEST 
function groupBy(arr, ...groupKeys) {
    const [key, ...restGroupKeys] = groupKeys;
    const groupObj = Object.entries(arr.reduce((result, item) => {
        const { [key]: grouKey, ...restProps } = item;
        const list = result[grouKey] = result[grouKey] || [];
        list.push(restProps);
        return result
    }, []));
    
    return groupObj.map(([groupKey, children]) => {
        return { 
            [key]: groupKey, 
            children: restGroupKeys.length ? groupBy(children, ...restGroupKeys) : children
        }
    })
}

groupBy(arr, 'country', 'reputation');



版权声明:本文为gd81325原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。