我有一个数组:

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

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

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


当前回答

另一种解决方案是创建查找对象:

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和对象将被共享。

其他回答

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

最近,我不得不面对同样的事情,我需要从一个巨大的数组中搜索字符串。

经过一番搜索,我发现用简单的代码就能轻松处理:

代码:

var items = mydata.filter(function(item){
    return item.word.toLowerCase().startsWith( 'gk );
})

看见https://jsfiddle.net/maheshwaghmare/cfx3p40v/4/

只要浏览器支持ECMA-262,第5版(2009年12月),这应该可以工作,几乎只有一行:

var bFound = myArray.some(function (obj) {
    return obj.id === 45;
});

以下是我将如何在纯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'

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