如何在javascript中将普通的对象数组转换为多级数组?

时间:2018-03-22 08:48:03

标签: javascript jquery arrays node.js object

我这样的普通数组对象:

var b = [
    {id: 1, name: 'England',parent_id: null},
    {id: 2, name: 'Spain',parent_id: null},
    {id: 3, name: 'Chelsea',parent_id: 1},
    {id: 4, name: 'Manchester United',parent_id: 1},
    {id: 5, name: 'Real Madrid',parent_id: 2},
    {id: 6, name: 'Barcelona',parent_id: 2},
    {id: 7, name: 'Hazard',parent_id: 3},
    {id: 8, name: 'Morata',parent_id: 3},
    {id: 9, name: 'Pogba',parent_id: 4},
    {id: 10, name: 'Lukaku',parent_id: 4},
    {id: 11, name: 'Ronaldo',parent_id: 5},
    {id: 12, name: 'Bale',parent_id: 5},
    {id: 13, name: 'Messi',parent_id: 6},
    {id: 14, name: 'Suarez',parent_id: 6},
];

我想将对象数组转换为:

var b = [
    {
        name: 'England',
        children: [
            {
                name: 'Chelsea',
                children: [
                    {name: 'Hazard'},
                    {name: 'Morata'}
                ]
            },
            {
                name: 'Manchester United',
                children: [
                    {name: 'Pogba'},
                    {name: 'Lukaku'}
                ]
            }
        ]
    },
    {
        name: 'Spain',
        children: [
            {
                name: 'Real Madrid',
                children: [
                    {name: 'Ronaldo'},
                    {name: 'Bale'}
                ]
            },
            {
                name: 'Barcelona',
                children: [
                    {name: 'Messi'},
                    {name: 'Suarez'}
                ]
            },
        ]
    }
];

似乎将使用关键的parent_id

分隔

但我仍然很难实现它

如何像这样转换数组对象?

请帮帮我们

1 个答案:

答案 0 :(得分:3)

  1. .filter() b因此它仅包含parent_id: null
  2. 的项目
  3. .map()剩余项目,将孩子分配给他们
  4. 每个根级父级的
  5. .map()子级返回时没有parent_id字段(可选,不在示例中)
  6. var b = [
        {id: 1, name: 'England',parent_id: null},
        {id: 2, name: 'Spain',parent_id: null},
        {id: 3, name: 'Chelsea',parent_id: 1},
        {id: 4, name: 'Manchester United',parent_id: 1},
        {id: 5, name: 'Real Madrid',parent_id: 2},
        {id: 6, name: 'Barcelona',parent_id: 2},
        {id: 7, name: 'Hazard',parent_id: 3},
        {id: 8, name: 'Morata',parent_id: 3},
        {id: 9, name: 'Pogba',parent_id: 4},
        {id: 10, name: 'Lukaku',parent_id: 4},
        {id: 11, name: 'Ronaldo',parent_id: 5},
        {id: 12, name: 'Bale',parent_id: 5},
        {id: 13, name: 'Messi',parent_id: 6},
        {id: 14, name: 'Suarez',parent_id: 6},
    ];
    
    const done = b.filter(person => !person.parent_id).map(person => {
    
      return {
        id      : person.id,
        name    : person.name,
        children: b.filter(child => child.parent_id == person.id)
      }
    
    });
    
    console.log(done);