选择具有指定值的所有对象

时间:2012-04-25 15:02:51

标签: javascript jquery object

使用jQuery或普通javascript

如果我有一个像这样的对象数组:

    [
    {"company":"acme", "Employees":10, "location":"Cork"}, 
    {"company":"foo", "Employees":50, "location":"Limerick"},
    {"company":"bar", "Employees":10, "location":"Dublin"}
    {"company":"zanzo", "Employees":23, "location":"Dublin"}
    ]

我可以方便地查询这些数据吗?

e.g。让所有拥有20多名员工的公司,或让所有公司都位于都柏林

提前致谢

1 个答案:

答案 0 :(得分:2)

您可以使用.grep()功能。例如:

var companiesWithOver20Employees = $.grep(companies, function(company, index) {
    return company.Employees > 10;
});

或:

var companiesInDublin = $.grep(companies, function(company, index) {
    return company.location == 'Dublin';
});