我有一个数组:
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实现这一点?
当前回答
我认为最简单的方法是以下方法,但它在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
其他回答
如果多次执行此操作,则可以设置映射(ES6):
const map = new Map( myArray.map(el => [el.id, el]) );
然后,您可以简单地执行O(1)查找:
map.get(27).foo
我认为最简单的方法是以下方法,但它在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
我真的很喜欢Aaron Digulla提供的答案,但需要保留我的对象数组,以便稍后可以迭代。所以我把它改成
var索引器={};对于(var i=0;i<array.length;i++){索引器[array[i].id]=parseInt(i);}//然后可以使用以下命令访问数组中的对象财产数组[索引器[id]].properties
使用find()方法:
myArray.find(x => x.id === '45').foo;
来自MDN:
如果数组中的元素满足所提供的测试函数,find()方法将返回数组中的第一个值。否则返回undefined。
如果要查找其索引,请使用findIndex():
myArray.findIndex(x => x.id === '45');
来自MDN:
findIndex()方法返回数组中满足所提供测试函数的第一个元素的索引。否则返回-1。
如果要获取匹配元素的数组,请改用filter()方法:
myArray.filter(x => x.id === '45');
这将返回一个对象数组。如果要获取foo财产数组,可以使用map()方法:
myArray.filter(x => x.id === '45').map(x => x.foo);
附带说明:旧浏览器(如IE)不支持find()或filter()和arrow函数等方法,因此如果您想支持这些浏览器,应该使用Babel(带有polyfill)来转换代码。
另一种解决方案是创建查找对象:
var lookup = {};
for (var i = 0, len = array.length; i < len; i++) {
lookup[array[i].id] = array[i];
}
... now you can use lookup[id]...
如果需要进行多次查找,这一点尤其有趣。
这将不需要更多的内存,因为ID和对象将被共享。