过滤对象数组javascript

时间:2017-12-22 12:34:33

标签: javascript arrays javascript-objects

我有这个对象数组:

var vigilantes = [
    {
        "fullName": "Tony Stark",
        "classRoom": "XI",
        "city": "NYC",
        "job": "Engineer",
        "studies": "MIT",
        "markAV": 10,
    },
    {
        "fullName": "Hulk Green",
        "classRoom": "IV",
        "city": "Beijing",
        "job": "Physicist",
        "studies": "Harvard",
        "markAV": 9,
    },
    {
        "fullName": "Thor Norse",
        "classRoom": "XX",
        "city": "Oslo",
        "job": "God",
        "studies": "U of Norway",
        "markAV": 8.5,
    },
    {
        "fullName": "Bruce Wayne",
        "classRoom": "XIX",
        "city": "Gotham",
        "job": "Richamn",
        "studies": "U of Gotham",
        "markAV": 8,
    },
    {
        "fullName": "Peter Parker",
        "classRoom": "XI",
        "city": "NYC",
        "job": "Photographer",
        "studies": "Syracuse U",
        "markAV": 7.5,
    }
]

我想按城市过滤它,但我需要创建一个包含共享同一城市的对象的新数组。在此示例中,所需的结果将是两个对象的数组,因为它们将NYC共享为城市:

var vigilantes = [
    {
        "fullName": "Tony Stark",
        "classRoom": "XI",
        "city": "NYC",
        "job": "Engineer",
        "studies": "MIT",
        "markAV": 10,
    },    
    {
        "fullName": "Peter Parker",
        "classRoom": "XI",
        "city": "NYC",
        "job": "Photographer",
        "studies": "Syracuse U",
        "markAV": 7.5,
    }
]

我知道我可以按照这样过滤城市:

var nyc = "NYC"
var oslo = "Oslo"
var gotham = "Gotham"
var beijing = "Beijing"

var res = vigilantes.filter(function (vigilante) {
  return beijing.indexOf(vigilante.city) >= 0; 
});

但我正在寻找更轻松的事情!

非常感谢你的帮助,因为你可以看到我是编程方面的新手!

1 个答案:

答案 0 :(得分:0)

您可以将哈希表作为对具有相同城市的数组的引用。



.as-console-wrapper { max-height: 100% !important; top: 0; }

wp_count_posts