Search nested array of objects

Pak Developer

I'm using ReactJs where I need to search in array of objects

Here is array

const menuList = [
  {
    title: "Top 1",
    link: "top1",
  },
  {
    title: "Top 2",
    link: "top2",
    children: [
      {
        title: "Top 2",
        link: "top2",
        parent: true
      },
      {
        title: "Top 2 child 1",
        link: "top2-child-1",
      },
      {
        title: "Top 2 children 2",
        link: "top2-child-2",
        children: [
          {
            title: "deep nested child",
            link: "deep-nested-child"
          }
        ]
      },
      {
        title: "Top 2 child 2",
        link:"top2-child-2"
      },
      {
        title: "Top 2 child 3",
        link: "top2-child-3",
        children: [
          {
            title: "Nested child of Child 3",
            link: "nested-child-of-3"
          }
        ]
      }
    ]
  }
];

I want to search based on link But I want to search first in deep childs then the top one. Search start from the deepest children and go to top until it find the match. If no match found it will return the same menuList back. If any match found then I want to get back whole array of this level not the single object.

For example if I search top2-child-1 then it should return.

     [
      {
        title: "Top 2",
        link: "top2",
        parent: true
      },
      {
        title: "Top 2 child 1",
        link: "top2-child-1",
      },
      {
        title: "Top 2 children 2",
        link: "top2-child-2",
        children: [
          {
            title: "deep nested child",
            link: "deep-nested-child"
          }
        ]
      },
      {
        title: "Top 2 child 2",
        link:"top2-child-2"
      },
      {
        title: "Top 2 child 3",
        link: "top2-child-3",
        children: [
          {
            title: "Nested child of Child 3",
            link: "nested-child-of-3"
          }
        ]
      }
    ]

What I'm trying is here.

const find_nested_link = (menuList, path) => {
  for (let i = 0; i < menuList.length; i++) {
    if (menuList[i].children) {
      return find_nested_link(menuList[i].children, path);
    } else {
      if (menuList[i].link === path) {
        return menuList;
      }
    }
  }
};

It will work only for first deep nested child. if you search nested-child-of-3 it will not able to find it.

Here is another one which is also not work perfect.

const result = menuList.reduce((r, { children }) => {
  let o = children.filter(({ link }) => link === path);
  if (o && o.length) r.push(...children);
  return r;
}, []);
Gandzal

I have provided two methods below:

  1. Search for first match in the tree, return if found and containing array.
  2. Search for all matches, returns containing array, object it was found in, and depth it was found at

Method 1: CodeSandbox

Here is a recursive method that doesnt use reduce. Simple type checking to search for a provided key value, and will search through any child arrays, with names that do not have to be "children". It provides a "found" result as well as an array in which it was found. You could extend this to return the object in which it was found too, quite easily.

const recursivelyFindKeyValue= (key, keyValue, list) => {
  console.log("Searching list: ", list);

  for (let i = 0; i < list.length; i++) {
    const item = list[i];

    for (const key of Object.keys(item)) {
      //check if its array of more options, search it
      if (Array.isArray(item[key])) {
        console.log("child array found, searching", item);
        const res = recursivelyFindKeyValue(key, keyValue, item[key]);
        if (res.found === true) return res;
      }
      //Test the keyValue
      else if (item[key] === keyValue) {
        //found, return the list
        console.log("found ", keyValue);
        return { found: true, containingArray: list };
      }
    }
  }

  return { found: false, containingArray: [] };
};

usage

const res = recursivelyFindKeyValue("link", "top2-child-2", menuList);
const res = recursivelyFindKeyValue("link", "nested-child-of-3", menuList);

Method 2: CodeSandbox

This method will search the entire tree, return all results with their parent array, object which they key:value was found, as well as the depth at which it was found.

const recursivelyFindKeyValue = (key, keyValue, list, depth = 0) => {
  console.log("Searching list: ", list);
  let results = [];

  for (let i = 0; i < list.length; i++) {
    const item = list[i];

    for (const key of Object.keys(item)) {
      //check if its not an array
      if (Array.isArray(item[key])) {
        console.log("child array found, searching", item);
        let res = recursivelyFindKeyValue(key, keyValue, item[key], depth + 1);
        results = results.concat(res);
      }
      //we have found it
      else if (item[key] === keyValue) {
        //found, return the list
        console.log("found ", keyValue);
        results.push({
          found: true,
          containingArray: list,
          depth: depth,
          object: item
        });
      }
    }
  }

  return results;
};

I created another link "top2-child-2" in the codesandbox example deeper down so you can see the result of multiple depths.

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

Search nested array of objects and return full parents as results in JavaScript

分類Dev

Search nested array of objects and return the full path to the object

分類Dev

Flattening deeply nested array of objects

分類Dev

Vue access nested array objects

分類Dev

Destruct nested array of objects javascript

分類Dev

Convert array of objects with nested array of objects into array-like object

分類Dev

Regroup array of objects based on nested array

分類Dev

How to make an array of multiple nested objects?

分類Dev

why map() is mutating original objects in a nested array?

分類Dev

Unable to convert a nested object into an array of objects and viceversa

分類Dev

Filtering deeply nested array of objects in Mongo DB

分類Dev

Angular: Nested ngFor on array of objects with FormArray

分類Dev

How to search for a value in array of objects and get it in Laravel?

分類Dev

how to query nested array of objects by also filtering nested array of nested array in mongo

分類Dev

Is it possible to search nested objects in ElasticSearch with the lucene query syntax?

分類Dev

How to get the combination of array values from nested arrays in an array of objects

分類Dev

javascript return property value from nested array of objects based on condition

分類Dev

Finding a path to target object in nested array of objects in Javascript

分類Dev

Mongoose Save Nested Array of Objects-Node.js

分類Dev

using decodable to capture array of nested objects in single line

分類Dev

How to use reduce to retrieve values from deep nested array objects

分類Dev

ManagedObjectContext does not 'get dirty' on edit of a nested array of objects

分類Dev

Is serializing objects nested inside array differently using FormData?

分類Dev

Nested ng-repeat with array of objects which contain arrays

分類Dev

Building a nested tree of data from plain array of objects

分類Dev

How to flat array of objects which can contain nested objects in my case

分類Dev

Search MongoDB Array of Objects where property has same value for more than 1 array element

分類Dev

Filtering nested objects Javascript

分類Dev

Nested objects to relational format

Related 関連記事

  1. 1

    Search nested array of objects and return full parents as results in JavaScript

  2. 2

    Search nested array of objects and return the full path to the object

  3. 3

    Flattening deeply nested array of objects

  4. 4

    Vue access nested array objects

  5. 5

    Destruct nested array of objects javascript

  6. 6

    Convert array of objects with nested array of objects into array-like object

  7. 7

    Regroup array of objects based on nested array

  8. 8

    How to make an array of multiple nested objects?

  9. 9

    why map() is mutating original objects in a nested array?

  10. 10

    Unable to convert a nested object into an array of objects and viceversa

  11. 11

    Filtering deeply nested array of objects in Mongo DB

  12. 12

    Angular: Nested ngFor on array of objects with FormArray

  13. 13

    How to search for a value in array of objects and get it in Laravel?

  14. 14

    how to query nested array of objects by also filtering nested array of nested array in mongo

  15. 15

    Is it possible to search nested objects in ElasticSearch with the lucene query syntax?

  16. 16

    How to get the combination of array values from nested arrays in an array of objects

  17. 17

    javascript return property value from nested array of objects based on condition

  18. 18

    Finding a path to target object in nested array of objects in Javascript

  19. 19

    Mongoose Save Nested Array of Objects-Node.js

  20. 20

    using decodable to capture array of nested objects in single line

  21. 21

    How to use reduce to retrieve values from deep nested array objects

  22. 22

    ManagedObjectContext does not 'get dirty' on edit of a nested array of objects

  23. 23

    Is serializing objects nested inside array differently using FormData?

  24. 24

    Nested ng-repeat with array of objects which contain arrays

  25. 25

    Building a nested tree of data from plain array of objects

  26. 26

    How to flat array of objects which can contain nested objects in my case

  27. 27

    Search MongoDB Array of Objects where property has same value for more than 1 array element

  28. 28

    Filtering nested objects Javascript

  29. 29

    Nested objects to relational format

ホットタグ

アーカイブ