Reputation: 703
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 ?
Upvotes: 2
Views: 6752
Reputation: 3810
You can compare 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));
Upvotes: 0
Reputation: 37755
You just need to extract the property you want to compare
const object = [ {name: 'John', age: 15},{name: 'Victor', age: 15},{name: 'Emile', age: 14}]
let op = object.every(({ age }) => age === 15)
console.log(op)
Upvotes: 2
Reputation: 1933
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.
Upvotes: 4