Answer the question
In order to leave comments, you need to log in
What is the fastest way to search through an array of objects?
There is an array of objects of the form:
[{
id:123,
name: 'Name1'
},{
id: 321,
name: 'Name2'
}]
{
123: {
id:123,
name: 'Name1'
},
321: {
id: 321,
name: 'Name2'
}
}
Answer the question
In order to leave comments, you need to log in
If the project uses jQuery, then I think it makes sense to refer to jQuery.grep :
var source = [{
id:123,
name: 'Name1'
},{
id: 321,
name: 'Name2'
}];
function getObject(source, id) {
return jQuery.grep(source, function(e){ return e.id == id; });
}
console.log(getObject(source, 321));
function getObject(source, id) {
for (var i = 0, len = source.length; i < len; i++) {
if (source[i].id == id) {
return source[i];
}
}
}
function getObject(source, id) {
return source.find(function (el) {
return el.id === id;
});
}
function getObject(source, id) {
return source.filter(function(el) {
return el.id === id;
})[0];
}
console.time('test_func_exec');
for (var i = 0; i < 10000000; i++) {
getObject(source, 123);
}
console.timeEnd('test_func_exec');
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question