How do you filter an array of JavaScript objects based on property conditions? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you filter an array of JavaScript objects based on property conditions?

message-square
0

To filter an array of JavaScript objects based on property conditions, call Array.prototype.filter() with a predicate callback that inspects each object’s properties and returns true for items that match or false to exclude them. Because filter() returns a new array without mutating the original array, you can safely combine multiple conditions (&& / ||), guard against missing or nullish fields (using optional chaining ?. or nullish coalescing ??), and compose reusable filter predicates.


1. Filtering Objects with Single and Multiple Property Conditions

Pass a predicate function to array.filter((item) => ...) that evaluates one or more property checks and returns a boolean:

// Filter an array of objects by exact match, comparison, and combined conditions
function filterOrders(orders, { status, minTotal, searchText } = {}) {
  if (!Array.isArray(orders)) {
    throw new TypeError("Expected orders to be an array.");
  }

  const normalizedQuery = typeof searchText === "string"
    ? searchText.trim().toLowerCase()
    : "";

  return orders.filter((order) => {
    if (!order || typeof order !== "object") {
      return false;
    }

    const matchesStatus = !status || order.status === status;
    const matchesTotal = typeof minTotal !== "number" || (order.total ?? 0) >= minTotal;
    const customerName = String(order.customer?.name ?? "").toLowerCase();
    const matchesSearch = !normalizedQuery || customerName.includes(normalizedQuery);

    return matchesStatus && matchesTotal && matchesSearch;
  });
}

// Example usage:
const orders = [
  { id: 1, status: "paid", total: 120, customer: { name: "Tariq Mahmood" } },
  { id: 2, status: "pending", total: 45, customer: { name: "Sana Ali" } },
  { id: 3, status: "paid", total: 310, customer: { name: "Zainab Raza" } }
];

console.log(filterOrders(orders, { status: "paid", minTotal: 100 }));
// [{ id: 1, ... }, { id: 3, ... }]
  • Non-mutating return value: filter() leaves the original array untouched and returns a new array containing matching object references.
  • Normalize string comparisons: Convert both sides with .toLowerCase() (and .trim()) for reliable case-insensitive text filtering.

2. Handling Nested Properties, Missing Keys, and null/undefined

Real-world object arrays often contain optional nested objects, missing keys, or null values that can throw errors if accessed directly:

// Safely filter objects with optional nested fields and missing keys
function filterActiveUsersByCity(users, cityName) {
  if (!Array.isArray(users) || typeof cityName !== "string") {
    return [];
  }

  const targetCity = cityName.trim().toLowerCase();

  return users.filter((user) => {
    const isActive = Boolean(user?.active);
    const userCity = String(user?.profile?.address?.city ?? "").trim().toLowerCase();
    return isActive && userCity === targetCity;
  });
}

// Example usage:
const users = [
  { id: "u1", active: true, profile: { address: { city: "Lahore" } } },
  { id: "u2", active: true, profile: null },
  { id: "u3", active: false, profile: { address: { city: "Lahore" } } }
];

console.log(filterActiveUsersByCity(users, "lahore"));
// [{ id: "u1", active: true, profile: { address: { city: "Lahore" } } }]
  • Optional chaining (?.): Prevents TypeError: Cannot read properties of null/undefined when traversing nested properties.
  • Explicit truthiness vs. falsy values: Use explicit comparisons (like item.count > 0 or item.role !== undefined) rather than relying on truthiness when 0, "", or false are valid values.

3. Building Reusable or Dynamic Filter Predicates

When filter criteria come from form inputs, query parameters, or multiple reusable rules, build a predicate or array of predicates so the filtering logic stays modular:

// Compose dynamic property predicates cleanly
function createObjectMatcher(criteriaList) {
  if (!Array.isArray(criteriaList) || criteriaList.length === 0) {
    return () => true;
  }

  return (item) =>
    item !== null &&
    typeof item === "object" &&
    criteriaList.every((predicate) => predicate(item));
}

// Example usage:
const products = [
  { sku: "A1", category: "audio", inStock: true, price: 85 },
  { sku: "A2", category: "audio", inStock: false, price: 210 },
  { sku: "K1", category: "keyboards", inStock: true, price: 140 }
];

const isAvailableAudioUnder150 = createObjectMatcher([
  (p) => p.category === "audio",
  (p) => p.inStock === true,
  (p) => p.price <= 150
]);

console.log(products.filter(isAvailableAudioUnder150));
// [{ sku: "A1", category: "audio", inStock: true, price: 85 }]
  • Array.prototype.every() for AND logic: Requires every predicate in the list to pass for an object to be kept.
  • Array.prototype.some() for OR logic: Keeps an object if at least one predicate in a group matches.

TL;DR: Use array.filter((obj) => ...) to return a new array of objects matching your property conditions—combining checks with && / ||, guarding nested or missing fields with ?. and ??, and using explicit comparisons when 0, "", or false are valid values.