使用嵌套对象展平数组 [英] Flatten an array with nested objects
本文介绍了使用嵌套对象展平数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含对象的数组,可以有多个子对象,这些子对象具有与父对象相同的结构,基本上只是对象嵌套.
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))
这篇关于使用嵌套对象展平数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文