返回字段为1的所有元素的函数

时间:2017-01-19 14:15:39

标签: javascript angularjs

我有阵列:

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。有什么建议?提前致谢。

3 个答案:

答案 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);