只想获取数组里的第三层的id 应该要怎么做?

只想获取数组里的第三层的id 应该要怎么做?

1、多层数组嵌套,只想返回单独返回最后一层的id 为[2,3,5,6,...]应该怎么做?

[

{

id: 1,

age: 23,

name: bear,

children: [

{

id: 2,

age: 24,

name: bear2

},

{

id: 3,

age: 24,

name: bear3

},

],

},

{

id: 4,

age: 26,

name: bear2,

children: [

{

id: 5,

age: 24,

name: bear4

},

{

id: 6,

age: 24,

name: bear5

},

],

}

]


回答:

混分。。^_^

let a = [

{ id: 1, children: [{ id: 2 }] },

{ id: 3, children: [] }

];

function func(arr) {

return arr.reduce((a, b) => {

return b.children ? [...a, ...func(b.children)] : [...a, b.id];

}, []);

}

console.log(func(a));


回答:

[

{

id: 1,

age: 23,

children: [

{

id: 2,

age: 24,

},

{

id: 3,

age: 24,

},

],

},

{

id: 3,

age: 26,

children: [

{

id: 4,

age: 24,

},

{

id: 5,

age: 24,

},

],

}

].reduce((acc,cur)=>(cur.children.forEach(({id})=>acc.push(id)),acc),[])

// [2, 3, 4, 5]


回答:

var arr = [

{

id: 1,

name: "bear1",

children: [

{

name: "bear12"

},

{

id: 3,

name: "bear13"

},

],

},

{

id: 3,

name: "bear2",

children: [

],

}

];

arr.reduce((result, item) => {

// 3

(item.children || []).some(node => node.id) && result.push(item);

// 2

(item.children || []).some(node => node.id && result.push(node));

// 1

result.push(item);

(item.children || []).some(node => node.id && result.push(node));

return result

}, [])

吐槽一下你的题目不清晰,感觉有3钟理解
1.获取 children 里面带 id 的项,构成数组
2.获取 children 里面带 id 的项,和 对应的父节点内容,构成数组(不清楚 children 部分是否需要)
3.根据 children 是否带 id 的项,过滤父节点

以上是 只想获取数组里的第三层的id 应该要怎么做? 的全部内容, 来源链接: utcz.com/p/936134.html

回到顶部