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
3 Answers
Reset to default 4You 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
版权声明:本文标题:javascript - check every values in array of object - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742223287a2435589.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论