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
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.