How to Get the First Matching JavaScript Object by Property Value in an Array of Objects?

Using Array.prototype.find()

The Array.prototype.find() method returns the first element that satisfies the condition in the provided callback function. You can use this to return the first matching object in an array of objects, for example, in the following way:

// ES6+
const employees = [
    { name: 'John', department: 'sales' },
    { name: 'Wayne', department: 'marketing' },
    { name: 'David', department: 'IT' },
    { name: 'Bruce', department: 'marketing' },
];

const firstMatch = employees.find((emp) => emp.department === 'marketing');

console.log(firstMatch); // {name: "Wayne", department: "marketing"}

If a match is not found then the Array.prototype.find() method will return undefined.

You can also directly unpack the object in the callback function's argument, for example, like so:

// ES6+
// ...
const firstMatch = employees.find(({ department }) => department === 'marketing');
// ...

Using a Loop

If you're unable to support ES6, then you can simply use a loop (such as a for loop) to iterate over the array till you find the first match. For example:

const employees = [
    { name: 'John', department: 'sales' },
    { name: 'Wayne', department: 'marketing' },
    { name: 'David', department: 'IT' },
    { name: 'Bruce', department: 'marketing' },
];

let match;

for (let i = 0; i < employees.length; i++) {
    if (employees[i].department === 'marketing') {
        match = employees[i];
        break;
    }
}

console.log(match); // {name: "Wayne", department: "marketing"}

In case a match is not found, "match" will be undefined.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.