2017-01-19 45 views
-3

我有數組:函數返回所有其中字段是元素1

var tabs = [ 

    { "id": 1, "Name": "Top","Paris":1,"London":1, "Rome":1}, 
    { "id": 2, "Name": "Best","Paris":1,"London":0,"Rome":0}, 
    { "id": 3, "Name": "Cheap","Paris":0,"London":1,"Rome":0} 

]; 

我想編寫接收作爲參數的鎮的一個函數(倫敦,巴黎或羅馬)每次都不同並返回參數爲1的數組元素。例如,我想獲取所有London=1的元素。有什麼建議麼?先謝謝了。

+0

爲什麼角???? –

回答

1

您可以使用Array.filter

function filterList(cityName) { 
    return tabs.filter(function(o) { 
     return o[cityName] === 1; 
    }); 
} 
1

var tabs= [ 
 

 
{ "id": 1, "Name": "Top","Paris":1,"London":1, "Rome":1}, 
 
{ "id": 2, "Name": "Best","Paris":1,"London":0,"Rome":0}, 
 
{ "id": 3, "Name": "Cheap","Paris":0,"London":1,"Rome":0} 
 

 
]; 
 

 
var getElementsWith=function(array,name){ 
 
    var myElements=[]; 
 
    array.forEach(function(tab){ 
 
    if(tab[name]===1) 
 
     myElements.push(tab); 
 
    }); 
 
    return myElements; 
 
    }; 
 

 
console.log(getElementsWith(tabs,"Paris"));

0

你可以使用一個通用的函數,該函數數組,鍵和值,你正在尋找。然後使用Array#filter作爲子集。

function filter(array, key, value) { 
 
    return array.filter(function (object) { 
 
     return object[key] === value; 
 
    }); 
 
} 
 

 
var tabs = [{ "id": 1, "Name": "Top","Paris":1,"London":1, "Rome":1 },{ "id": 2, "Name": "Best","Paris":1,"London":0,"Rome":0 },{ "id": 3, "Name": "Cheap","Paris":0,"London":1,"Rome":0 }], 
 
    result = filter(tabs, 'London', 1); 
 

 
console.log(result);

相關問題