使用嵌套对象展平数组
问题描述:
我有一个包含对象的数组,可以有多个子对象,这些子对象具有与父对象相同的结构,基本上只是对象嵌套.
I have an array with objects, that can have children, the children have the same structure as the parent, it's just object nesting basically.
我想知道如何展平对象的结构,以便获得所有对象的ID,包括嵌套对象的ID.
例如,此结构
const data = [
{
id: 2,
children: [
{
id: 1,
children: []
}
]
},
{
id: 3,
children: [],
}
]
应对此扁平化
const data = [2,1,3]
我已经尝试了
使用Array.reduce()和对象散布语法,但是我无法完全理解执行此操作所需的逻辑.
I've tried
Using Array.reduce() and the object spread syntax, but I can't wrap my head around the logic required to do this.
答
const data = [
{
id: 2,
children: [
{
id: 1,
children: []
}
]
},
{
id: 3,
children: [],
}
]
const getIds = (data) => data.map(d => [d.id, ...getIds(d.children)]).flat()
console.log(getIds(data))