我有一个数组:
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实现这一点?
当前回答
我真的很喜欢Aaron Digulla提供的答案,但需要保留我的对象数组,以便稍后可以迭代。所以我把它改成
var索引器={};对于(var i=0;i<array.length;i++){索引器[array[i].id]=parseInt(i);}//然后可以使用以下命令访问数组中的对象财产数组[索引器[id]].properties
其他回答
尝试以下操作
function findById(source, id) {
for (var i = 0; i < source.length; i++) {
if (source[i].id === id) {
return source[i];
}
}
throw "Couldn't find object with id: " + id;
}
以下是我将如何在纯JavaScript中实现它,以我所能想到的在ECMAScript 3或更高版本中工作的最简单的方式。一旦找到匹配项,它就会返回。
var getKeyValueById = function(array, key, id) {
var testArray = array.slice(), test;
while(test = testArray.pop()) {
if (test.id === id) {
return test[key];
}
}
// return undefined if no matching id is found in array
return;
}
var myArray = [{'id':'73', 'foo':'bar'}, {'id':'45', 'foo':'bar'}]
var result = getKeyValueById(myArray, 'foo', '45');
// result is 'bar', obtained from object with id of '45'
myArray.filter(function(a){ return a.id == some_id_you_want })[0]
我认为最简单的方法是以下方法,但它在Internet Explorer 8(或更早版本)上不起作用:
var result = myArray.filter(function(v) {
return v.id === '45'; // Filter out the appropriate one
})[0].foo; // Get result and access the foo property
你可以试试Sugarjshttp://sugarjs.com/.
它在Arrays上有一个非常好的方法,.find。所以你可以找到这样的元素:
array.find( {id: 75} );
您还可以向其传递具有更多财产的对象,以添加另一个“where-clause”。
请注意,Sugarjs扩展了本地对象,有些人认为这非常邪恶。。。