给定对象数组,找到具有特定键的对象 [英] Given an array of objects, find the object with a particular key
问题描述
给定一个对象数组,在JS中使用特定键查找对象的最佳方法是什么?
Given an array of objects, what is the best way to find the object with a particular key in JS?
使用jQuery和underscoreJS很好.我只是在寻找最简单/最少的代码答案.
Using jQuery and underscoreJS is fine. I'm just looking for the easiest / least code answer.
示例: 对象数组,其中每个对象都有一个名称".查找具有特定名称"的对象.
Example: An array of objects, where each object has a "name". Find the object with a particular "name".
var people = [{name: "A"}, {name: "B"}, {name: "C"}];
我当前的解决方案: 传入数组,键(例如名称")和值(例如"C").
My current solution: Pass in the array, the key (e.g. "name"), and the value (e.g. "C").
function getObject(myArray, searchKey, searchValue) {
myArray.forEach(function(element){
if (element[searchKey] == searchValue) {
return element;
}
});
}
推荐答案
您可以使用Underscore.js的 _.where
函数,像这样
You can use Underscore.js's _.where
function, like this
console.log(_.where(people, {
"name": "C"
}));
# [ { name: 'C' } ]
这将返回数组中的所有对象,该对象与我们作为第二个参数传递的对象完全匹配.
This returns all the objects in the array, which exactly matches the object we pass as the second argument.
这篇关于给定对象数组,找到具有特定键的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!