javascript - Better way to find object in array instead of looping? -
example
link: http://jsfiddle.net/ewbgt/
var test = [{ "name": "john doo" }, { "name": "foo bar" }] var find = 'john doo' console.log(test.indexof(find)) // output: -1 console.log(test[find]) // output: undefined $.each(test, function(index, object) { if(test[index].name === find) console.log(test[index]) // problem: way slow })
problem
in above example have array objects. need find object has name = 'john doo'
my .each
loop working, part executed 100 times , test contain lot more objects. think way slow.
the indexof()
won't work because cannot search name in object.
question
how can search object name = 'john doo'
in current array?
jquery $.grep
(or other filtering function) not optimal solution.
the $.grep
function loop through all elements of array, if searched object has been found during loop.
from jquery grep documentation :
the $.grep() method removes items array necessary remaining items pass provided test. test function passed array item , index of item within array. if test returns true item in result array.
provided array not sorted, nothing can beat this:
var getobjectbyname = function(name, array) { // (!) cache array length in variable (var = 0, len = test.length; < len; i++) { if (test[i].name === name) return test[i]; // return object found } return null; // searched object not found }
Comments
Post a Comment