我有一个数组:

myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}, etc.]

我无法更改阵列的结构。我收到了一个45的id,我想得到数组中该对象的“bar”。

如何在JavaScript或使用jQuery实现这一点?


当前回答

您可以使用map()函数轻松实现这一点:

myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}];

var found = $.map(myArray, function(val) {
    return val.id == 45 ? val.foo : null;
});

//found[0] == "bar";

工作示例:http://jsfiddle.net/hunter/Pxaua/

其他回答

从aggaton的答案开始,这是一个实际返回所需元素(如果找不到则返回null)的函数,给定数组和一个回调函数,该函数返回“正确”元素的truthy值:

function findElement(array, callback) {
    var elem;
    return array.some(function(e) {
        if (callback(e)) {
            elem = e;
            return true;
        }
    }) ? elem : null;
});

请记住,这在IE8-上本就不起作用,因为它不支持某些功能。可以提供polyfill,或者总是有经典的for循环:

function findElement(array, callback) {
    for (var i = 0; i < array.length; i++)
        if (callback(array[i])) return array[i];
    return null;
});

它实际上更快、更紧凑。但如果你不想重新发明轮子,我建议使用下划线或lodash之类的实用程序库。

我认为最简单的方法是以下方法,但它在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

正如其他人所指出的,.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);//找不到对象时未定义

动态缓存查找

在这个解决方案中,当我们搜索某个对象时,我们将其保存在缓存中。这是“始终搜索解决方案”和“为预先计算的每个对象创建哈希图”之间的中间点。

让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);//高速缓存的

即使在纯JavaScript中,也可以通过对数组使用内置的“filter”函数来实现这一点:

Array.prototype.filterObjects = function(key, value) {
    return this.filter(function(x) { return x[key] === value; })
}

所以现在只需用“id”代替key,用“45”代替value,就会得到与id 45匹配的完整对象。那就是,

myArr.filterObjects("id", "45");