JavaScript Recursive Search in Array of Objects

Learn how to recursively search an array of objects in JavaScript, find nested objects by ID, return all matches, and search child arrays safely.

Published

Updated

Read time 3 min read

Reviewed byDeepak Prasad

JavaScript Recursive Search in Array of Objects

A recursive search is useful when an array of objects contains nested child arrays. Common examples include menu items, comments, folder trees, category trees, and API responses where each object may contain more objects inside children.

A normal find() works for one flat array. For nested arrays of objects, write a function that checks the current level and then searches each child array until it finds a match.

Environment: Node.js v20.18.2. After each runnable snippet, the following paragraph states the expected console output (order and values).


Method 1: Find One Object by ID Recursively

This function returns the first object whose id matches the target ID.

javascript
const items = [
  {
    id: 1,
    name: "root",
    children: [
      { id: 2, name: "docs" },
      { id: 3, name: "src", children: [{ id: 4, name: "app.js" }] },
    ],
  },
];

function findById(nodes, id) {
  for (const node of nodes) {
    if (node.id === id) {
      return node;
    }

    const found = node.children && findById(node.children, id);
    if (found) {
      return found;
    }
  }
}

console.log("recursive-find:", findById(items, 4).name);
Output

You should see one line logging recursive-find: app.js.

The function stops as soon as it finds a match, which is useful when IDs are unique.


Method 2: Return undefined When Nothing Matches

If no object matches, the function returns undefined.

javascript
const result = findById(items, 99);
console.log(result);
Output

You should see one line logging undefined.

Callers should check the result before accessing properties.


Method 3: Find All Matching Objects Recursively

Use an accumulator when you need every match, not only the first match.

javascript
function findAll(nodes, predicate, results = []) {
  for (const node of nodes) {
    if (predicate(node)) {
      results.push(node);
    }

    if (node.children) {
      findAll(node.children, predicate, results);
    }
  }

  return results;
}

const matches = findAll(items, (item) => item.name.includes("s"));
console.log(matches.map((item) => item.name));
Output

You should see one line logging [ 'docs', 'src' ].

This version traverses the whole tree because more matches may exist after the first one.


Method 4: Search Different Child Property Names

Not every API uses children. Some use items, nodes, folders, or subcategories. Make the child key configurable.

javascript
function findNested(nodes, predicate, childKey = "children") {
  for (const node of nodes) {
    if (predicate(node)) return node;

    const children = node[childKey];
    if (Array.isArray(children)) {
      const found = findNested(children, predicate, childKey);
      if (found) return found;
    }
  }
}
Output

This keeps the recursive search reusable across different object shapes.


Can Array.find search nested arrays?

Array.find() searches only the current array. It does not automatically search nested child arrays, so nested data needs recursion or flattening first.

Should recursive search return one match or all matches?

Return one match when IDs are unique or you only need the first result. Return an array of matches when multiple nested objects can satisfy the condition.

How do I avoid errors when children is missing?

Check Array.isArray(node.children) or use node.children && ... before recursively searching child nodes.


Summary

To recursively search an array of objects in JavaScript, loop through the current array, test each object, and recursively search its child array when present. Return immediately for the first match, or collect results in an array when you need every matching object. This pattern works well for nested menus, comments, categories, folder structures, and tree-shaped API data.


Official Documentation

Olorunfemi Akinlua

Boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs …