1

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?

2 Answers 2

10

Just use .every instead of .some? Arrow functions will make it more concise too:

const checkExists = (check, arr) => arr.every(el => el.check === check);
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.