2011-04-21 47 views
2

我需要搜索具有搜索项的对象的对象数组,并获取数组中的结果索引。javascript根据搜索条件查找对象

比方说,我有一个这样的数组:

[ 
    { 
    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", 
    } 
] 

现在我需要搜索数组:

{ 
    gender: "female" 
} 

,并得到结果:

[ 0, 3 ] 

搜索对象可以是任意长度:

{ 
    gender: "female", 
    colorChoice: "red" 
} 

什么是最清洁和最高性能的方式来搜索数组?

谢谢。

+0

相关:http://stackoverflow.com/questions/3624741/searching-for-objects-in-javascript-arrays – 2011-04-21 08:01:57

+0

你应该得到[0,3]从数组你当下。 – KooiInc 2011-04-21 08:20:16

+0

@KooiInc谢谢 – Harry 2011-04-21 08:33:56

回答

2

这里的想法:

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(); 
} 

看到jsfiddle

而且更通用:

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(); 
} 

看到jsfiddle

+0

任何原因你反向遍历数组? – TJHeuvel 2011-04-21 08:37:13

+2

速度更快。参见http://devpro.it/examples/loopsbench/或http://codeutopia.net/blog/2009/04/30/optimizing-javascript-for-extreme-performance-and-low-memory-消费/ – KooiInc 2011-04-21 08:47:24

+0

这很聪明,因为类型juggeling确保当我<= 0时停止!你不得不改变你的我 - - - 虽然:) – TJHeuvel 2011-04-21 09:05:01

2

这应该做的伎俩:

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; 
} 

例如:

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", 
    } 
])); 
+0

您可以编辑函数以返回数组的索引(i),只需将它推到结果数组而不是项目上即可。 – TJHeuvel 2011-04-21 08:28:59

+0

谢谢,这看起来不错 – Harry 2011-04-21 08:35:22

+0

如果你喜欢它,你可以将它标记为答案:) – TJHeuvel 2011-04-21 08:46:15