0

I have this array object

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

What i need is to make a new array that will only have active customers, that new array will look like

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

Because you may see there is only one active customer?

3
  • The activeCustomers variable you have is not valid JSON. There's an extra end-brace. Also, do you want office to be 1? It seems like you would want the office to retain the same value since you never mentioned otherwise. Commented Sep 29, 2014 at 14:34
  • This is not json, it objects in array Commented Sep 29, 2014 at 14:36
  • JSON stands for JavaScript Object Notation and activeCustomers is not valid. Commented Sep 29, 2014 at 14:37

2 Answers 2

1

You can use .filter on the array.prototype (MDN reference)

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

Note: You'll have to use the MDN polyfill for browser support below IE9.

Sign up to request clarification or add additional context in comments.

2 Comments

active: 1, id: 1name: "1"office: "<button data-id=2 class='btn btn-danger'><i class='fa fa-trash fa-lg'></i> Delete record</button>"position: "1"
It doesn not retunr prover way, now first is active?
1

You can use the jQuery function grep:

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

Note that this will work in all browsers; the alternative approach would be to use Array.filter which is a (relatively) new addition to JavaScript and will fail in some older browsers.

2 Comments

Please make sure you have my latest edit (I missed off the return statement initially)
Giving answers via a 'fiddle' (or other external link) is discouraged on this site, if the link breaks the answer becomes useless. I've tested this against your array and it worked fine for me, doesn't it work for you?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.