How to Check If an Object Property Value Exists in a JavaScript Array of Objects?

Learn how to check if a property value exists in an array of objects in JavaScript

Let's suppose we have an array of objects like the following:

const objs = [
    { id: 1, name: 'John' },
    { id: 2, name: 'Jane' },
    { id: 3, name: 'David' },
    { id: 4, name: 'Zayne' },
];

If we wanted to check if, for example, the name property with a specific value exists in the objects array, we could do it in the following ways:

Using some()

Introduced in ES5, the some() method returns a boolean value. It tests whether at least one element in the array satisfies the test condition (which is implemented by the provided function). We can use this to test if a key in the object of arrays has a certain value in the following way:

// ES5+
console.log(objs.some((obj) => obj.name === 'John')); // output: true

In ES6+, we can destructure function arguments to simplify the syntax even more. For example:

// ES6+
console.log(objs.some(({ name }) => name === 'John')); // output: true

Using a for Loop

If you're unable to use the latest features of JavaScript, then perhaps you can rely on a simple for loop to check if a key in the object of arrays has a certain value. For example:

let found = false;

for (let i = 0; i < objs.length; i++) {
    if (objs[i].name === 'John') {
        found = true;
        break;
    }
}

console.log(found); // output: true

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