我这样的普通数组对象:
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
分隔但我仍然很难实现它
如何像这样转换数组对象?
请帮帮我们
答案 0 :(得分:3)
.filter()
b
因此它仅包含parent_id: null
.map()
剩余项目,将孩子分配给他们.map()
子级返回时没有parent_id
字段(可选,不在示例中)
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);