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

后端 未结 7 890
慢半拍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

    This will use recursive find by level, it'll try to find the item in array and then call itself with the children of each item in the array:

    New browsers will have Array.prototype.flatten but in this case I've added the flatten function separately.

    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 flatten = (arr) =>
      arr.reduce((result, item) => result.concat(item), []);
    const findBy = (findFunction, subItemsKey) => (array) =>
      //array is empty (can be when children of children of children does not exist)
      array.length === 0
        ? undefined //return undefined when array is empty
        : array.find(findFunction) || //return item if found
          findBy(findFunction, subItemsKey)(//call itself when item is not found
            flatten(
              //take children from each item and flatten it
              //([[child],[child,child]])=>[child,child,child]
              array.map((item) => item[subItemsKey] || []),
            ),
          );
    const findChildrenById = (array) => (value) =>
      findBy((item) => item.id === value, 'children')(array);
    const findInArray = findChildrenById(array);
    
    console.log('found', findInArray(99));
    console.log('not found', findInArray({}));

提交回复
热议问题