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

夏天
  • 3
新手上路,请多包涵

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
            },
        ],
    }
]
回复
阅读 379
3 个回答
✓ 已被采纳

混分。。^_^

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 的项,过滤父节点

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
你知道吗?

宣传栏