使用jQuery筛选数组

Filter an array using jQuery

本文关键字:数组 筛选 jQuery 使用      更新时间:2023-09-26

我有这个数组对象

var customers = [{
    "id": "1",
    "name": "1",
    "position": "1",
    "office": "<button data-id=2 class='btn btn-danger'><i class='fa fa-trash fa-lg'></i> Delete record</button>",
    "active": "1"
}, {
    "id": "2",
    "name": "2",
    "position": "2",
    "office": "<button data-id=2 class='btn btn-danger'><i class='fa fa-trash fa-lg'></i> Delete record</button>",
    "active": 0
}];

我需要的是制作一个只有活跃客户的新阵列,这个新阵列看起来像

var activeCustomers = [{
    "id": "1",
    "name": "1",
    "position": "1",
    "office": "1",
    "active":"1"
}
}];

因为你可能看到只有一个活跃的客户?

您可以在阵列原型(MDN参考)上使用.filter

var activeCustomers = customers.filter(function(customer) { return customer.active; });

注意:您必须使用MDN polyfill来支持IE9以下的浏览器。

您可以使用jQuery函数grep:

var activeCustomers = $.grep(customers, function(c){return c.active;});

请注意,这将适用于所有浏览器;另一种方法是使用Array.filter,这是JavaScript的一个(相对)新添加,在一些旧的浏览器中会失败。