javascript 根据搜索词查找对象
我需要使用搜索词对象搜索对象数组,并获取数组中结果的索引。
假设我有一个像这样的数组:
[
{
name: "Mary",
gender: "female",
country: "USA",
orientation: "straight",
colorChoice: "red",
shoeSize: 7
},
{
name: "Henry",
gender: "male",
country: "USA",
orientation: "straight",
colorChoice: "red",
},
{
name: "Bob",
colorChoice: "yellow",
shoeSize: 10
},
{
name: "Jenny",
gender: "female",
orientation: "gay",
colorChoice: "red",
}
]
现在我需要在数组中搜索:
{
gender: "female"
}
并获取结果:
[ 0, 3 ]
搜索对象可以是任意长度:
{
gender: "female",
colorChoice: "red"
}
搜索数组最干净、最高效的方法是什么?
谢谢。
I need to search an array of objects with an object of search terms and get the index of results in an array.
Let's say I have an array like this:
[
{
name: "Mary",
gender: "female",
country: "USA",
orientation: "straight",
colorChoice: "red",
shoeSize: 7
},
{
name: "Henry",
gender: "male",
country: "USA",
orientation: "straight",
colorChoice: "red",
},
{
name: "Bob",
colorChoice: "yellow",
shoeSize: 10
},
{
name: "Jenny",
gender: "female",
orientation: "gay",
colorChoice: "red",
}
]
Now I need to search the array for:
{
gender: "female"
}
and get result:
[ 0, 3 ]
The search object can be any length:
{
gender: "female",
colorChoice: "red"
}
What's the cleanest and most performant way to search the array?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是想法:
请参阅 jsfiddle
更通用:
请参阅 jsfiddle
Here's the idea:
see jsfiddle
And more generic:
see jsfiddle
这应该可以解决问题:
例如:
This should do the trick:
For example: