我有一个数组:
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实现这一点?
当前回答
动态缓存查找
在这个解决方案中,当我们搜索某个对象时,我们将其保存在缓存中。这是“始终搜索解决方案”和“为预先计算的每个对象创建哈希图”之间的中间点。
让cachedFind=(()=>{let cache=new Map();return(arr,id,el=null)=>cache.get(id)||(el=arr.find(o=>o.id==id),cache.set(id,el),el);})();// ---------//测试// ---------let myArray=[…Array(100000)].map((x,i)=>({‘id‘:‘${i}‘,‘foo‘:‘bar_${i}‘}));//示例用法console.log(cachedFind(myArray,'1234').foo);//基准让板凳=(id)=>{console.time('time for'+id);console.log(cachedFind(myArray,id).foo);//查找console.timeEnd('time for'+id);}console.log('-----无缓存-----');工作台(50000);工作台(79980);工作台(99990);console.log('-----缓存-----');工作台(79980);//高速缓存的工作台(99990);//高速缓存的
其他回答
我认为最简单的方法是以下方法,但它在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
此解决方案也可能有帮助:
Array.prototype.grep = function (key, value) {
var that = this, ret = [];
this.forEach(function (elem, index) {
if (elem[key] === value) {
ret.push(that[index]);
}
});
return ret.length < 2 ? ret[0] : ret;
};
var bar = myArray.grep("id","45");
我将其设置为$.grep,如果找到一个对象,函数将返回该对象,而不是数组。
我真的很喜欢Aaron Digulla提供的答案,但需要保留我的对象数组,以便稍后可以迭代。所以我把它改成
var索引器={};对于(var i=0;i<array.length;i++){索引器[array[i].id]=parseInt(i);}//然后可以使用以下命令访问数组中的对象财产数组[索引器[id]].properties
Use:
var retObj ={};
$.each(ArrayOfObjects, function (index, obj) {
if (obj.id === '5') { // id.toString() if it is int
retObj = obj;
return false;
}
});
return retObj;
它应该按id返回一个对象。