2011-04-21 36 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