I have an array of objects, something like this:
var myArray = [
{ 'name' : 'some name', id: 23131, 'has' : ['dogs'] },
{ 'name' : 'some name 2', id: 8678, 'has' : ['dogs', 'cats'] },
{ 'name' : 'some name 3', id: 2125 , 'has' : ['donkeys', 'goats']},
{ 'name' : 'some name 4', id: 90867, 'has' : ['parrots', 'treasure'] },
{ 'name' : 'some name 5', id: 435458, 'has' : undefined },
];
And I want to retrieve specific elements that match certain criteria. For example, a person whose name contains number 5, and id is 435458. Or a person who has a parrot or a goat, or both.
The method I'm trying to build takes two arguments, value A and value B. Value A is an object, like { 'name' : '5' }
or { 'name' : /5/ }
or { 'name' : 5 }
or { 'has' : 'goats' }, and value B is the object to match against, i.e. myArray
.
The method is quickly becoming quite complex and I feel that my code is not quite as effective and efficient as it could.
I think the best way to achieve this is to loop through the objects and arrays that are passed and found (myArray
, has
array), and call it self until there only two string/number/regexp values to be compared against. But I'm not quite sure on how to best achieve this. Or is this not the best way to go? Also, speed is an important success criterion.
Cheers
Edit: http://jsbin.com/ediye/edit contains the function I'm using now, and I think it works as described above, but its quite slow for large data sets.