最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 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);

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
发布评论

评论列表(0)

  1. 暂无评论