我有阵列:
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 :(得分:1)
{{1}}
答案 2 :(得分: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);