admin管理员组

文章数量:1327945

I have an array of object like this :

const object = [
     {name: 'John', age: 15},
     {name: 'Victor', age: 15},
     {name: 'Emile', age: 14}
     ]

I need to check if in this array all age are 15. ( just need a boolean for answer ) I need to use something like 'every' method but how with an object ?

I have an array of object like this :

const object = [
     {name: 'John', age: 15},
     {name: 'Victor', age: 15},
     {name: 'Emile', age: 14}
     ]

I need to check if in this array all age are 15. ( just need a boolean for answer ) I need to use something like 'every' method but how with an object ?

Share Improve this question asked Apr 28, 2020 at 17:58 TheDevGuyTheDevGuy 7032 gold badges12 silver badges26 bronze badges 3
  • 2 every() works with an array. The callback function can check the property of the object. – Barmar Commented Apr 28, 2020 at 17:59
  • obj.age == 15 – Barmar Commented Apr 28, 2020 at 17:59
  • I asume you mean are 15 or older? – connexo Commented Apr 28, 2020 at 18:04
Add a ment  | 

3 Answers 3

Reset to default 4

You need to use every:

The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value. Array.prototype.every

So the code will be like:

const object = [
    {name: 'John', age: 15},
    {name: 'Victor', age: 15},
    {name: 'Emile', age: 14}
]
     
const isValid = object.every(item => item.age === 15)
console.log({isValid})

This is js functional ability to test all your elements states.

You just need to extract the property you want to pare

const object = [ {name: 'John', age: 15},{name: 'Victor', age: 15},{name: 'Emile', age: 14}]

let op = object.every(({ age }) => age === 15)

console.log(op)

You can pare the length of the array with length of array of objects with required age.

const object = [ 
    {name: 'John', age: 15},
    {name: 'Victor', age: 15},
    {name: 'Emile', age: 14}
];
function hasAge(pAge, object) {
    return object.length === object.filter(({ age }) => age === pAge).length;
}
console.log(hasAge(15, object));

本文标签: javascriptcheck every values in array of objectStack Overflow