查找ID对象在JavaScript中对象的数组 [英] Find object by id in an array of JavaScript objects
问题描述
我有一个数组:
myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}, etc.]
我无法改变阵列的结构。我被传递 45
的ID,我想获得'酒吧'
数组中的对象。
I'm unable to change the structure of the array. I'm being passed an id of 45
, and I want to get 'bar'
for that object in the array.
我如何做到这一点的JavaScript或使用jQuery?
How do I do this in JavaScript or using jQuery?
推荐答案
当你已经在使用jQuery,您可以使用的grep其目的是用于搜索的阵列的功能:
As you are already using jQuery, you can use the grep function which is intended for searching an array:
var result = $.grep(myArray, function(e){ return e.id == id; });
结果与找到的项目阵列。如果你知道对象是永远存在的,它只能出现一次,你可以使用结果[0]包含.foo
来获得的价值。否则,你应该检查所生成的数组的长度。例如:
The result is an array with the items found. If you know that the object is always there and that it only occurs once, you can just use result[0].foo
to get the value. Otherwise you should check the length of the resulting array. Example:
if (result.length == 0) {
// not found
} else if (result.length == 1) {
// access the foo property using result[0].foo
} else {
// multiple items found
}
这篇关于查找ID对象在JavaScript中对象的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!