How to check if all objects in an array of objects contains a key value pair.
For example consider this array = arr=[{name:'one',check:'1'},{name;'two',check:'0.1'},{name:'three',check:'0.01'}]
the below function returns true if atleast the check value is present in one object of array otherwise false. `
function checkExists(check,arr) {
return arr.some(function(el) {
return el.check === check;
});
}
`
But I need to check and return true only if all the objects in the array contain that check value otherwise false.
How to do this?
How to check if all objects in an array of objects contains a key value pair.
For example consider this array = arr=[{name:'one',check:'1'},{name;'two',check:'0.1'},{name:'three',check:'0.01'}]
the below function returns true if atleast the check value is present in one object of array otherwise false. `
function checkExists(check,arr) {
return arr.some(function(el) {
return el.check === check;
});
}
`
But I need to check and return true only if all the objects in the array contain that check value otherwise false.
How to do this?
Share Improve this question asked Aug 20, 2021 at 6:30 YadityaYaditya 477 bronze badges2 Answers
Reset to default 10Just use .every
instead of .some
? Arrow functions will make it more concise too:
const checkExists = (check, arr) => arr.every(el => el.check === check);
CertainPerformance answer is the one. But if you absolutely want to iterate like you did you just need to create an increment for the number of object that contains the desired key, then return if the increment value equals the number of values in the array.
let arr=[{name:'one',check:'1',hello:'boy'},
{name:'two',check:'0.1',bye:6},{name:'three',check:'0.01',bye:18}];
function checkExists(key,arr) {
let count = 0;
arr.forEach((el) => {
if(el.hasOwnProperty(key)){
count += 1;
}
});
return count === arr.length;
}
console.log(checkExists("name", arr)); // true
console.log(checkExists("check", arr)); // true
console.log(checkExists("hello", arr)); // false
console.log(checkExists("bye", arr)); // false