How do you check if an array of objects contains an item with a matching property value? | A1Lab@FahadM to JavaScriptEnglish • 5 days ago

How do you check if an array of objects contains an item with a matching property value?

message-square
0

To check if an array of objects contains at least one item with a matching property value in JavaScript, use Array.prototype.some(). .some() returns a boolean (true or false) and stops iterating as soon as it finds the first matching element, making it both readable and fast.


1. Checking for a Match with Array.prototype.some()

Pass a predicate function to .some() that compares the target property on each object against the desired value:

// Check whether any object in the array has a matching property value
const inventory = [
  { sku: "KB-101", name: "Mechanical Keyboard", inStock: true },
  { sku: "MS-204", name: "Wireless Mouse", inStock: false },
  { sku: "MN-309", name: "27-inch Monitor", inStock: true }
];

const hasOutOfStockItem = inventory.some((item) => item.inStock === false);
const hasKeyboardSku = inventory.some((item) => item.sku === "KB-101");

console.log("Has out-of-stock item:", hasOutOfStockItem); // true
console.log("Has SKU KB-101:", hasKeyboardSku);           // true
  • Returns a boolean (true / false): Ideal for conditional checks like guards, flags, or preventing duplicate entries.
  • Short-circuits early: Stops checking remaining items once a match returns true (and returns false immediately on an empty array).
  • Dynamic property lookup: Use a helper like hasItemWithProperty(arr, "role", "admin") with bracket notation item?.[propName] === targetValue when the key name is dynamic.

2. When You Also Need the Matching Object (.find()) or Index (.findIndex())

If you need more than a boolean—such as the matching object itself or its index in the array—use .find() or .findIndex() instead of running a second search:

// Retrieve the matching object with .find() or its position with .findIndex()
function findUserByEmail(users, targetEmail) {
  const normalizedTarget = targetEmail.trim().toLowerCase();
  return users.find(
    (user) => typeof user.email === "string" && user.email.toLowerCase() === normalizedTarget
  );
}

const users = [
  { id: 1, email: "ali@example.com", active: true },
  { id: 2, email: "sara@example.com", active: false }
];

const matchedUser = findUserByEmail(users, "SARA@example.com");
const matchedIndex = users.findIndex((user) => user.id === 2);

console.log("Matched user:", matchedUser);   // { id: 2, email: "sara@example.com", active: false }
console.log("Matched index:", matchedIndex); // 1
  • .find(): Returns the first matching object, or undefined if none match.
  • .findIndex(): Returns the first matching index (0 or greater), or -1 if no item matches.
  • Case-insensitive or trimmed matching: Normalize strings (trim(), toLowerCase()) before comparing when matching user input like emails or tags.

3. Common Traps to Avoid

Checking object arrays for matching property values trips developers up when reference equality or missing properties come into play:

  • Using .includes() on an array of objects: [ { id: 1 } ].includes({ id: 1 }) returns false because .includes() checks object reference identity (===), not deep or property equality—use .some() instead.
  • Accessing nested properties without optional chaining (item.meta.code): If item.meta is null or undefined on any element, accessing .code throws a TypeError; use item.meta?.code === target.
  • Using .filter().length > 0 unnecessarily: .filter() allocates a new array and scans every element even after finding a match on index 0, whereas .some() returns true immediately and avoids extra array allocation.

TL;DR: Use array.some((item) => item.prop === value) to check for a matching property value as a boolean, or .find() / .findIndex() when you also need the matching object or its index.

Are you checking for duplicate IDs/SKUs before inserting, matching nested/case-insensitive fields, or retrieving the matching object itself?