javascript find objects based on search terms
I need to search an array of objects with an object of se开发者_开发知识库arch terms and get the index of results in an array.
Let's say I have an array like this:
[
{
name: "Mary",
gender: "female",
country: "USA",
orientation: "straight",
colorChoice: "red",
shoeSize: 7
},
{
name: "Henry",
gender: "male",
country: "USA",
orientation: "straight",
colorChoice: "red",
},
{
name: "Bob",
colorChoice: "yellow",
shoeSize: 10
},
{
name: "Jenny",
gender: "female",
orientation: "gay",
colorChoice: "red",
}
]
Now I need to search the array for:
{
gender: "female"
}
and get result:
[ 0, 3 ]
The search object can be any length:
{
gender: "female",
colorChoice: "red"
}
What's the cleanest and most performant way to search the array?
Thanks.
Here's the idea:
function getFemales(myArr){
var i = myArr.length, ret = [];
while (i--){
if ('gender' in myArr[i] && myArr[i].gender === 'female') {
ret.push(i);
}
}
return ret.sort();
}
see jsfiddle
And more generic:
function findInElements(elArray, label, val){
var i = elArray.length, ret = [];
while (i--){
if (label in elArray[i] && elArray[i][label] === val) {
ret.push(i);
}
}
return ret.sort();
}
see jsfiddle
This should do the trick:
function searchArray(fields, arr)
{
var result = []; //Store the results
for(var i in arr) //Go through every item in the array
{
var item = arr[i];
var matches = true; //Does this meet our criterium?
for(var f in fields) //Match all the requirements
{
if(item[f] != fields[f]) //It doesnt match, note it and stop the loop.
{
matches = false;
break;
}
}
if(matches)
result.push(item); //Add the item to the result
}
return result;
}
For example:
console.log(searchArray({
gender: "female",
colorChoice: "red"
},[
{
name: "Mary",
gender: "female",
country: "USA",
orientation: "straight",
colorChoice: "red",
shoeSize: 7
},
{
name: "Henry",
gender: "male",
country: "USA",
orientation: "straight",
colorChoice: "red",
},
{
name: "Bob",
colorChoice: "yellow",
shoeSize: 10
},
{
name: "Jenny",
gender: "female",
orientation: "gay",
colorChoice: "red",
}
]));
精彩评论