我有一个数组:
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
其他回答
更通用和简短
function findFromArray(array,key,value) {
return array.filter(function (element) {
return element[key] == value;
}).shift();
}
在您的示例中,Ex.varelement=findFromArray(myArray,'id',45),它将为您提供整个元素。
你可以试试Sugarjshttp://sugarjs.com/.
它在Arrays上有一个非常好的方法,.find。所以你可以找到这样的元素:
array.find( {id: 75} );
您还可以向其传递具有更多财产的对象,以添加另一个“where-clause”。
请注意,Sugarjs扩展了本地对象,有些人认为这非常邪恶。。。
正如其他人所指出的,.find()是在数组中查找一个对象的方法。但是,如果无法使用此方法找到对象,则程序将崩溃:const myArray=[{'id':'73','o':'bar'},{'id':'45','o':'bar'}];const res=myArray.find(x=>x.id=='100').foo;//噢!/*错误:“Uncaught TypeError:无法读取未定义的属性'foo'”或在较新的chrome版本中:Uncaught TypeError:无法读取未定义的的财产(读取“foo”)*/
这可以通过在使用.foo之前检查.find()的结果是否已定义来解决。Modern JS允许我们通过可选链接轻松完成这一点,如果找不到对象,则返回undefined,而不是崩溃代码:
const myArray=[{'id':'73','o':'bar'},{'id':'45','o':'bar'}];const res=myArray.find(x=>x.id=='100')?。foo;//没有错误!console.log(res);//找不到对象时未定义
我们可以使用Jquery方法$.each()/$.grep()
var data= [];
$.each(array,function(i){if(n !== 5 && i > 4){data.push(item)}}
or
var data = $.grep(array, function( n, i ) {
return ( n !== 5 && i > 4 );
});
使用ES6语法:
Array.find, Array.filter, Array.forEach, Array.map
或使用Lodashhttps://lodash.com/docs/4.17.10#filter强调https://underscorejs.org/#filter
如果多次执行此操作,则可以设置映射(ES6):
const map = new Map( myArray.map(el => [el.id, el]) );
然后,您可以简单地执行O(1)查找:
map.get(27).foo