我有一个数组:
myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}, etc.]
我无法更改阵列的结构。我收到了一个45的id,我想得到数组中该对象的“bar”。
如何在JavaScript或使用jQuery实现这一点?
我有一个数组:
myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}, etc.]
我无法更改阵列的结构。我收到了一个45的id,我想得到数组中该对象的“bar”。
如何在JavaScript或使用jQuery实现这一点?
当前回答
查找数组索引的方法:
index = myArray.map((i) => i.id).indexOf(value_of_id);
item = myArray[index];
其他回答
您可以使用map()函数轻松实现这一点:
myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}];
var found = $.map(myArray, function(val) {
return val.id == 45 ? val.foo : null;
});
//found[0] == "bar";
工作示例:http://jsfiddle.net/hunter/Pxaua/
查找数组索引的方法:
index = myArray.map((i) => i.id).indexOf(value_of_id);
item = myArray[index];
我真的很喜欢Aaron Digulla提供的答案,但需要保留我的对象数组,以便稍后可以迭代。所以我把它改成
var索引器={};对于(var i=0;i<array.length;i++){索引器[array[i].id]=parseInt(i);}//然后可以使用以下命令访问数组中的对象财产数组[索引器[id]].properties
由于您已经在使用jQuery,因此可以使用grep函数来搜索数组:
var result = $.grep(myArray, function(e){ return e.id == id; });
结果是找到项的数组。如果您知道对象始终存在,并且它只出现一次,那么只需使用result[0].foo获取值。否则,应检查结果数组的长度。例子:
if (result.length === 0) {
// no result found
} else if (result.length === 1) {
// property found, access the foo property using result[0].foo
} else {
// multiple items found
}
你可以试试Sugarjshttp://sugarjs.com/.
它在Arrays上有一个非常好的方法,.find。所以你可以找到这样的元素:
array.find( {id: 75} );
您还可以向其传递具有更多财产的对象,以添加另一个“where-clause”。
请注意,Sugarjs扩展了本地对象,有些人认为这非常邪恶。。。