How to find a object in a nested array using recursion in JS

后端 未结 7 834
慢半拍i
慢半拍i 2021-01-04 21:58

Consider the following deeply nested array:

const array = [
    {
        id: 1,
        name: \"bla\",
        children: [
            {
                id:         


        
7条回答
  •  鱼传尺愫
    2021-01-04 22:09

    You can do:

    const array=[{id:1,name:"bla",children:[{id:23,name:"bla",children:[{id:88,name:"bla"},{id:99,name:"bla"}]},{id:43,name:"bla"},{id:45,name:"bla",children:[{id:43,name:"bla"},{id:46,name:"bla"}]}]},{id:12,name:"bla",children:[{id:232,name:"bla",children:[{id:848,name:"bla"},{id:959,name:"bla"}]},{id:433,name:"bla"},{id:445,name:"bla",children:[{id:443,name:"bla"},{id:456,name:"bla",children:[{id:97,name:"bla"},{id:56,name:"bla"}]}]}]},{id:15,name:"bla",children:[{id:263,name:"bla",children:[{id:868,name:"bla"},{id:979,name:"bla"}]},{id:483,name:"bla"},{id:445,name:"bla",children:[{id:423,name:"bla"},{id:436,name:"bla"}]}]}];
    const findItemNested = (arr, itemId, nestingKey) => arr.reduce((a, c) => {
      return a.length
        ? a
        : c.id === itemId
          ? a.concat(c)
          : c[nestingKey]
            ? a.concat(findItemNested(c[nestingKey], itemId, nestingKey))
            : a
    }, []);
    const res = findItemNested(array, 959, "children");
    
    if (res.length) {
      console.log(res[0]);
    }

提交回复
热议问题