给定一个对象数组,什么是在JS中用特定键查找对象的最佳方法?给定一个对象数组,找到一个特定的键对象
使用jQuery和underscoreJS很好。我只是在寻找最简单/最少的代码答案。
示例: 对象数组,其中每个对象都有一个“名称”。找到具有特定“名称”的对象。
var people = [{name: "A"}, {name: "B"}, {name: "C"}];
我当前的解决方案: 通行证的阵列中,所述键(例如, “名称”),并将该值(例如, “C”)。
function getObject(myArray, searchKey, searchValue) {
myArray.forEach(function(element){
if (element[searchKey] == searchValue) {
return element;
}
});
}
你可能想要'filter'。 – elclanrs 2014-11-04 05:01:05
太糟糕了ES6还没有真正支持:'返回arr.find(el => el [searchKey] === searchValue);' – 2014-11-04 05:05:38
@ Qantas94Heavy它仍然在草稿:( – thefourtheye 2014-11-04 05:06:36