在对象数组中搜索特定属性并返回布尔值
假设我有一个对象数组
let arr = [
{
name: "john",
age: 22
},
{
name: "george",
age: 55
}
];
和一个对象
let obj = {
name: "bill",
age: 55
}
,我想搜索所有 arr
对象以查找与 obj.age
年龄相同的任何人,并根据是否返回一个布尔值它是否包含相同的属性。
我显然可以这样做:
let find = arr.filter(i => i.age === obj.age);
let bool = find.length > 0 && true;
但是有没有办法调用一个方法(lodash、plain js 或其他)来通过设计来获得这个,如 method(arr,obj.age) //returns true
?
let arr = [
{
name: "john",
age: 22
},
{
name: "george",
age: 55
}
];
let obj = {
name: "bill",
age: 55
}
let find = arr.filter(i => i.age === obj.age);
let bool = find.length > 0 && true;
console.log(bool)
lets say i have an array of objects
let arr = [
{
name: "john",
age: 22
},
{
name: "george",
age: 55
}
];
and an object
let obj = {
name: "bill",
age: 55
}
and i want to search all arr
objects to find anyone with the same age as obj.age
and return a boolean depending whether it includes a same property or not.
i can obviously do :
let find = arr.filter(i => i.age === obj.age);
let bool = find.length > 0 && true;
but is there a way to call a method (lodash,plain js or whatever) to just get this by design like method(arr,obj.age) //returns true
?
let arr = [
{
name: "john",
age: 22
},
{
name: "george",
age: 55
}
];
let obj = {
name: "bill",
age: 55
}
let find = arr.filter(i => i.age === obj.age);
let bool = find.length > 0 && true;
console.log(bool)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
一些
。所以基本上,如果数组中的任何对象属性与所需值匹配,它将返回一个布尔值You can use
some
. So basically it will return a boolean value if any of the object property in array matches the required value我们可以通过两种方式做到这一点。我们可以使用 some 函数直接获取布尔值,或者通过 find 函数,我们可以使用 !! 将其转换为布尔值操作员。
we can do it in two ways. we can use the some function and get the boolean directly or by find function, we can convert it to a boolean using !! operator.