js数组算法问题

求实现该函数,处理数据,根据配置项合并数据相同项,再以树形展示。

/*
  * 处理数据 dealData
  * @param sourceData {array} 数据源
  * @param headerKeys {array} 分类key集合
  * @return 处理后数据
  * */
  const dealData = (sourceData, headerKeys) => {

  }
// 示例1
let source = [
    { province: '浙江', city: '杭州', dict: '萧山' },
    { province: '浙江', city: '杭州', dict: '滨江' },
    { province: '浙江', city: '杭州', dict: '上城' },
    { province: '浙江', city: '宁波', dict: '鄞州' },
    { province: '浙江', city: '宁波', dict: '北仑' },
    { province: '浙江', city: '宁波', dict: '余姚' },
    { province: '上海', city: '上海', dict: '浦东新区' },
  ]
  let header = ['province', 'city', 'dict']
  
  let r = dealData(source,header)
  /* r = [
    {
      province: '浙江',
      children: [
        {
          city: '杭州',
          children: ['萧山', '滨江', '上城']
        },
        {
          city: '宁波',
          children: ['鄞州', '北仑', '余姚']
        },
      ]
    },
    {
      province: '上海',
      children: [
        {
          city: '上海',
          children: ['浦东新区']
        }
      ]
    }
  ]*/
// 示例2
let source1 = [
    { a: 'a1', b: 'b1', c: 'c1' },
    { a: 'a1', b: 'b1', c: 'c2' },
    { a: 'a1', b: 'b3', c: 'c3' },
    { a: 'a2', b: 'b4', c: 'c4' },
    { a: 'a3', b: 'b5', c: 'c5' }
  ]
  let header1 = ['a', 'b']
  let r1 = dealData(source1,header1)
  /* r1 = [
    {
      a: 'a1',
      children: [
        { b: 'b1' },
        { b: 'b3' }
      ]
    },
    {
      a: 'a2',
      children: [
        { b: 'b4' }
      ]
    },
    {
      a: 'a3',
      children: [
        { b: 'b5' }
      ]
    }
  ]
*/
阅读 1.6k
1 个回答

image.png

// 示例1
let source = [
    { province: '浙江', city: '杭州', dict: '萧山' },
    { province: '浙江', city: '杭州', dict: '滨江' },
    { province: '浙江', city: '杭州', dict: '上城' },
    { province: '浙江', city: '宁波', dict: '鄞州' },
    { province: '浙江', city: '宁波', dict: '北仑' },
    { province: '浙江', city: '宁波', dict: '余姚' },
    { province: '上海', city: '上海', dict: '浦东新区' },
  ]
  let header = ['province', 'city', 'dict']
  
/*
  * 处理数据 dealData
  * @param sourceData {array} 数据源
  * @param headerKeys {array} 分类key集合
  * @return 处理后数据
  * */
  const dealData = (sourceData=[], headerKeys=[]) => {
let objMap = sourceData.reduce((acc,item)=>((((acc[item[headerKeys[0]]]||={})[item[headerKeys[1]]])||=[]).push(item[headerKeys[2]]),acc),{});
console.log(objMap);
return Object.entries(objMap).map(([province,provinceChildren])=>({province,children:Object.entries(provinceChildren).map(([city,children])=>({city,children}))}));

  }
  let r = dealData(source,header)
console.log(r);

类似问题
https://segmentfault.com/q/10...

推荐问题
宣传栏