2014-05-21 42 views
1

我有這樣搜索的JavaScript

var userdata = [ 
    {"id":1,"gender":"M","first":"John","last":"Smith","city":"Seattle, WA","status":"Active"}, 
    {"id":2,"gender":"F","first":"Kelly","last":"Ruth","city":"Dallas, TX","status":"Active"}, 
    {"id":3,"gender":"M","first":"Jeff","last":"Stevenson","city":"Washington, D.C.","status":"Active"}, 
    {"id":4,"gender":"F","first":"Jennifer","last":"Gill","city":"Seattle, WA","status":"Inactive"} 
] 

陣列我需要在一定條件下過濾此陣列。這些條件的形式是這樣的。

var search_object = {gender:"M",city:"Seattle, WA"} 
// Gender = M and city = 'Seattle, WA' 
var search_object1 = {gender:"M"} 
var search_object2 = {city:"Seattle, WA"} 
// This is same as above 
var search_array = {status:["Active","Inactive"]} 
// Status Active or Inactive 
var search_array = [{status:"Active"},{status:"Inactive"}] 
// Same as above 
var search_object1 = {gender:"F"} 
var search_array = [{status:"Active"},{status:"Inactive"}] 
//Gender = F and status = Active or Inactive 
var search_object = {gender:"F"} 
var search_array = [{status:["Active","Inactive"]}] 
// same as above 

我試過循環但失敗。請幫助或建議或提供一些適當的鏈接以獲得幫助。

+2

請發表您的循環。 – Hatsjoem

+0

我的意思是說,我不是JavaScript專家,並沒有提供'和'和'或'來過濾項目 –

+1

看起來像一個適當的函數工作[filter](https://developer.mozilla.org/en- US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) – CodingIntrigue

回答

7

以下代碼涵蓋了您提到的所有情況。

function search(searchObj, data) { 
    if(searchObj instanceof Array) { 
     return data.reduce(function(prev, current, index, array) { 
      return prev.concat(search(current, data)); 
     }, []); 
    } else { 
     var results = data.filter(function(el) { 
      for(var prop in searchObj) { 
       if(searchObj[prop] instanceof Array) { 
        if(searchObj[prop].indexOf(el[prop]) == -1) { 
         return false; 
        } 
       } else 
       if(el[prop] !== searchObj[prop]) { 
        return false; 
       } 
      } 

      return true; 
     }); 

     return results; 
    } 
}; 

search(search_object, userdata); 

以下是JSFiddle中的工作示例。

這裏有一些鏈接的功能我上面使用:

+0

這會返回空結果 –

+0

我已更新代碼並添加了小提琴。 –

+0

好的,根據您的更新,我也更新了我的解決方案。現在它涵蓋了所有的情況。一探究竟。 –

1

正是在評論中說的RGraham,你可以使用數組的過濾功能。

var search_object = {gender:"M",city:"Seattle, WA"}; 
var filtered = userdata.filter(function(obj){ 
    return (obj.gender === search_object && obj.city === search_object.city) 
}); 
filtered[0];//Array with objects that return true; 
+0

如何添加'obj.dynamic_column'來自條件不是'obj.gender' –