在 JavaScript 对象数组中按 id 查找对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7364150/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find object by id in an array of JavaScript objects
提问by thugsb
I've got an array:
我有一个数组:
myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}, etc.]
I'm unable to change the structure of the array. I'm being passed an id of 45
, and I want to get 'bar'
for that object in the array.
我无法更改数组的结构。我被传递了一个 id 45
,我想'bar'
在数组中获取该对象。
How do I do this in JavaScript or using jQuery?
如何在 JavaScript 或使用 jQuery 中执行此操作?
采纳答案by Micha? Per?akowski
Use the find()
method:
使用find()
方法:
myArray.find(x => x.id === '45').foo;
From MDN:
来自MDN:
The
find()
method returns the first value in the array, if an element in the array satisfies the provided testing function. Otherwiseundefined
is returned.
find()
如果数组中的元素满足提供的测试函数,则该方法返回数组中的第一个值。否则undefined
返回。
If you want to find its indexinstead, use findIndex()
:
如果你想找到它的索引,请使用findIndex()
:
myArray.findIndex(x => x.id === '45');
From MDN:
来自MDN:
The
findIndex()
method returns the index of the first element in the array that satisfies the provided testing function. Otherwise -1 is returned.
该
findIndex()
方法返回数组中满足提供的测试函数的第一个元素的索引。否则返回-1。
If you want to get an array of matching elements, use the filter()
method instead:
如果要获取匹配元素的数组,请改用该filter()
方法:
myArray.filter(x => x.id === '45');
This will return an array of objects. If you want to get an array of foo
properties, you can do this with the map()
method:
这将返回一个对象数组。如果您想获取一组foo
属性,可以使用以下map()
方法执行此操作:
myArray.filter(x => x.id === '45').map(x => x.foo);
Side note: methods like find()
or filter()
, and arrow functionsare not supported by older browsers (like IE), so if you want to support these browsers, you should transpile your code using Babel(with the polyfill).
附注:方法,如find()
或filter()
和箭头的功能不被旧的浏览器(如IE)的支持,所以如果你想支持这些浏览器,你应该使用transpile代码巴贝尔(用填充工具)。
回答by Guffa
As you are already using jQuery, you can use the grepfunction which is intended for searching an array:
由于您已经在使用 jQuery,您可以使用用于搜索数组的grep函数:
var result = $.grep(myArray, function(e){ return e.id == id; });
The result is an array with the items found. If you know that the object is always there and that it only occurs once, you can just use result[0].foo
to get the value. Otherwise you should check the length of the resulting array. Example:
结果是一个包含找到的项目的数组。如果您知道该对象始终存在并且只出现一次,则可以使用result[0].foo
来获取该值。否则,您应该检查结果数组的长度。例子:
if (result.length === 0) {
// no result found
} else if (result.length === 1) {
// property found, access the foo property using result[0].foo
} else {
// multiple items found
}
回答by Aaron Digulla
Another solution is to create a lookup object:
另一种解决方案是创建一个查找对象:
var lookup = {};
for (var i = 0, len = array.length; i < len; i++) {
lookup[array[i].id] = array[i];
}
... now you can use lookup[id]...
This is especially interesting if you need to do many lookups.
如果您需要进行多次查找,这尤其有趣。
This won't need much more memory since the IDs and objects will be shared.
这不需要更多内存,因为 ID 和对象将被共享。
回答by Rúnar Berg
ECMAScript 2015provides the find()method on arrays:
ECMAScript 2015提供了数组的find()方法:
var myArray = [
{id:1, name:"bob"},
{id:2, name:"dan"},
{id:3, name:"barb"},
]
// grab the Array item which matchs the id "2"
var item = myArray.find(item => item.id === 2);
// print
console.log(item.name);
It works without external libraries. But if you want older browser supportyou might want to include this polyfill.
它无需外部库即可工作。但是如果你想要旧的浏览器支持,你可能想要包含这个 polyfill。
回答by GijsjanB
Underscore.jshas a nice method for that:
Underscore.js有一个很好的方法:
myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'},etc.]
obj = _.find(myArray, function(obj) { return obj.id == '45' })
回答by pimvdb
I think the easiest way would be the following, but it won't work on Internet Explorer 8 (or earlier):
我认为最简单的方法如下,但它不适用于 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
回答by JaredPar
Try the following
尝试以下
function findById(source, id) {
for (var i = 0; i < source.length; i++) {
if (source[i].id === id) {
return source[i];
}
}
throw "Couldn't find object with id: " + id;
}
回答by Danilo Colasso
myArray.filter(function(a){ return a.id == some_id_you_want })[0]
回答by will Farrell
A generic and more flexible version of the findById function above:
上面 findById 函数的通用且更灵活的版本:
// array = [{key:value},{key:value}]
function objectFindByKey(array, key, value) {
for (var i = 0; i < array.length; i++) {
if (array[i][key] === value) {
return array[i];
}
}
return null;
}
var array = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}];
var result_obj = objectFindByKey(array, 'id', '45');
回答by hunter
You can get this easily using the map()function:
您可以使用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";
Working example: http://jsfiddle.net/hunter/Pxaua/