Search JSON Objects Recursively in JavaScript

Tech reviewed: Deepak Prasad
Search JSON Objects Recursively in JavaScript

Recursive search in JavaScript is useful when you need to find a value inside a nested JSON object. It walks through the object tree until it finds the match or reaches the end of the structure.

This pattern is common in filters, settings objects, API payloads, and nested records. If your JSON comes from text first, JSON.parse and JavaScript string contains often appear nearby in the same workflow.

Tested on: Node.js v20.18.2. A short note after each runnable snippet describes what you should see in the console.


Method 1: Search for a value recursively

The recursive function checks primitive values first and then walks each nested property.

javascript
function search(obj, target) {
  if (obj === null || typeof obj !== "object") {
    return obj === target ? obj : undefined;
  }

  for (const value of Object.values(obj)) {
    const result = search(value, target);
    if (result !== undefined) {
      return result;
    }
  }
}

const data = {
  team: {
    name: "Dev",
    contact: { email: "[email protected]" },
  },
};

console.log("json-find:", search(data, "[email protected]"));
Output

You should see one line logging json-find: [email protected].

Use this when you want to find a specific nested value in a JSON object.


Method 2: Search nested arrays and objects together

The same function can walk arrays because arrays are also objects in JavaScript.

javascript
const mixed = {
  users: [{ name: "Ana" }, { name: "Ben" }],
  meta: { role: "admin" },
};

console.log("json-search-array:", search(mixed, "Ben"));
Output

You should see one line logging json-search-array: Ben.

This is useful when the data structure contains nested lists as well as nested objects.


Method 3: Return the first matching value

Returning as soon as you find a match keeps the traversal efficient for lookup tasks.

javascript
console.log("json-search-first:", search({ a: { b: "x" }, c: "y" }, "y"));
Output

You should see one line logging json-search-first: y.

Use this when you only need one match and do not need to collect every occurrence.


Summary

Recursive JSON search in JavaScript is a clean way to find nested values in objects and arrays. Use it when the structure is unknown, nested, or too deep for a simple direct lookup.


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 user-friendly interfaces to enhance digital …

  • JavaScript
  • Web Design