简体   繁体   中英

Checking an array if all objects inside contains a given key value(javascript)

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?

Just 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM