本文翻譯自:Find object by id in an array of JavaScript objects
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中做到這一點?#1樓
參考:https://stackoom.com/question/Utkc/通過ID在JavaScript對象數組中查找對象
#2樓
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');
#3樓
You may try out Sugarjs from http://sugarjs.com/ .
您可以從http://sugarjs.com/試用Sugarjs。It has a very sweet method on Arrays,
.find
.
它在數組.find
上有一個非常好的方法。 So you can find an element like this:
是以,您可以找到這樣的元素:array.find( {id: 75} );
You may also pass an object with more properties to it to add another "where-clause".
您還可以将具有更多屬性的對象傳遞給它,以添加另一個“ where-clause”。Note that Sugarjs extends native objects, and some people consider this very evil...
請注意,Sugarjs擴充了本機對象,有些人認為這非常邪惡。#4樓
Underscore.js has 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' })
#5樓
Use:
采用:var retObj ={};
$.each(ArrayOfObjects, function (index, obj) {
if (obj.id === '5') { // id.toString() if it is int
retObj = obj;
return false;
}
});
return retObj;
It should return an object by id.
它應該通過id傳回一個對象。#6樓
You can use filters,
您可以使用過濾器function getById(id, myArray) {
return myArray.filter(function(obj) {
if(obj.id == id) {
return obj
}
})[0]
}
get_my_obj = getById(73, myArray);