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

后端 未结 7 827
慢半拍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:10

    We use object-scan for most of our data processing. It's awesome for all sorts of things, but does take a while to wrap your head around. This is how one could answer your question:

    const objectScan = require('object-scan');
    
    const find = (data, id) => objectScan(['**(^children$).id'], {
      abort: true,
      rtn: 'parent',
      useArraySelector: false,
      filterFn: ({ value }) => value === id
    })(data);
    
    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"}]}]}];
    
    console.log(find(array, 12));
    // => { id: 12, name: 'bla', children: [ { id: 232, name: 'bla', children: [Array] }, { id: 433, name: 'bla' }, { id: 445, name: 'bla', children: [Array] } ] }
    console.log(find(array, 483));
    // => { id: 483, name: 'bla' }
    console.log(find(array, 959));
    // => { id: 959, name: 'bla' }
    console.log(find(array, 1200));
    // => undefined
    

提交回复
热议问题