2014-09-29 62 views
0

阵列我有这个数组对象过滤器使用jQuery

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" 
} 
}]; 

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

+0

您所拥有的'activeCustomers'变量是无效的JSON。还有一个额外的支架。另外,你想'办公室'是1?看起来你会希望'办公室'保持相同的价值,因为你从来没有提到过。 – 2014-09-29 14:34:39

+0

这不是json,它在数组中对象 – 2014-09-29 14:36:09

+0

JSON代表JavaScript Object Notation和'activeCustomers'无效。 – 2014-09-29 14:37:38

回答

1

您可以在array.prototype(MDN reference

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

注意使用.filter:你必须使用MDN填充工具下面IE9浏览器的支持。

+0

你有试过吗? – 2014-09-29 13:57:14

+0

是的...它的工作原理。 – 2014-09-29 14:30:03

+0

请给我们工作小提琴 – 2014-09-29 14:33:53

1

您可以使用jQuery的功能grep

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

注意,这将在所有的浏览器;另一种方法是使用Array.filter这是一个相对较新的JavaScript新增功能,并且在某些较旧的浏览器中会失败。

+0

This return empty – 2014-09-29 13:55:42

+0

请确保您有我最近的编辑(我最初错过了退货声明) – codebox 2014-09-29 13:58:03

+0

任何工作小提琴 – 2014-09-29 14:34:40