Skip to content
Advertisement

Search nested array of objects and return whole path of all matching items

I would like to search a deeply nested array of objects and return the path of all matched objects. I have partial solution of the problem but the code returns path of only first matched object. Please have a look at the input, expected output and the code itself. I have commented the desired logic in the expected output section.

Thanks in advance. Please help me out.

The Input Data

JavaScript

Expected Output – if sofa is searched

JavaScript

Expected Output – if furniture is searched

JavaScript

The code

JavaScript

Advertisement

Answer

This looks like it will do it:

JavaScript
JavaScript

We separate out the recursive filtering mechanism, and also the object-matching part, putting them back together in filterMatches. The idea is that we might want to filter by many means, so the function takes an arbitrary predicate function that can test the current node. testIncludes takes an object of key-value pairs and returns a function which takes an object and reports whether the object’ corresponding keys each includes the relevant value. (I added case-insensitive checking here based on your input / requested output combination.)

Note that I named the central function with the word filter rather than find, as find generally implies returning the first match, whereas filter is supposed to return all matches.


For my own use, I would structure the main function slightly differently:

JavaScript

I like these curried functions a great deal, and with the parameters in that order I feel they are most useful. But YMMV.

Update

A comment noted a lint failure for the main function. It’s an understandable one, as this did something tricky in using an assignment inside a conditional expression. So here are some working variants:

  • Moving the assignment to a default parameter:

    JavaScript

    Pros:

    • This keeps our expression-only style alive, and avoids the trickiness above.
    • It’s fairly easy to read

    Cons:

    • It uses default parameters, which have their problems.
    • It requires naming two unused parameters from flatMat (Here _ and __.)
  • Using statement style:

    JavaScript

    Pros:

    • No more trickiness of any sort
    • More accessible for beginners

    Cons:

    • if and return are statements and statements lead to less modular code than working with pure expressions.
  • Using a call helper function:

    JavaScript

    Pros:

    • A call helper function is all-around useful and can be reused in many places.
    • It avoids any fiddling with parameters

    Cons:

    • This combines the last two clauses of what is really a three-part test (returning [x], returning [{... x, children: kids}], and returning []) into a single function

I have a slight preference for that last version. But any of them would do.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement