How to filter nested objects in JavaScript ?


To filter nested objects in JavaScript, we can use the filter() method along with the map() method to iterate over the nested objects and filter them based on a condition. Here are a few methods to do it:

Method 1: Using the filter() and map() methods with Object.entries()

const data = {
  id: 1,
  name: "John",
  address: {
    city: "New York",
    state: "NY",
    country: "USA"
  },
  orders: [
    { id: 1, product: "Phone", price: 1000 },
    { id: 2, product: "Laptop", price: 2000 },
    { id: 3, product: "Tablet", price: 500 }
  ]
};

const filteredOrders = data.orders.filter(order => order.price > 1000);

const filteredData = {
  ...data,
  orders: filteredOrders
};

console.log(filteredData);

Output:

{
  id: 1,
  name: "John",
  address: {
    city: "New York",
    state: "NY",
    country: "USA"
  },
  orders: [
    { id: 2, product: "Laptop", price: 2000 }
  ]
}

Method 2: Using the filter() and map() methods with recursion

const data = {
  id: 1,
  name: "John",
  address: {
    city: "New York",
    state: "NY",
    country: "USA"
  },
  orders: [
    { id: 1, product: "Phone", price: 1000 },
    { id: 2, product: "Laptop", price: 2000 },
    { id: 3, product: "Tablet", price: 500 }
  ]
};

const filterNestedObjects = (obj, condition) => {
  return Object.keys(obj).reduce((acc, key) => {
    if (typeof obj[key] === "object") {
      acc[key] = filterNestedObjects(obj[key], condition);
    } else if (Array.isArray(obj[key])) {
      acc[key] = obj[key].filter(item => condition(item));
    } else {
      acc[key] = obj[key];
    }
    return acc;
  }, {});
};

const filteredData = filterNestedObjects(data, item => item.price > 1000);

console.log(filteredData);

Output:

{
  id: 1,
  name: "John",
  address: {
    city: "New York",
    state: "NY",
    country: "USA"
  },
  orders: [
    { id: 2, product: "Laptop", price: 2000 }
  ]
}

In both methods, we are filtering the orders array based on the condition that the price of the order is greater than 1000. The first method creates a new object with the filtered orders array, while the second method uses recursion to filter nested objects and arrays.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.