Reputation: 9660
I have a collection of Customer objects inside the JavaScript Array.
var customer = Customer();
customer.firstName = "John";
customer.isEnabled = true
var customer2 = Customer();
customer2.firstName = "Mary";
customer2.isEnabled = false
var customers = [customer,customer2];
Now, I want to return true if any of the objects inside the customers array property "isEnabled" = false. Basically I want a way to validate a property of every object that is inside the array (customers).
UPDATE:
So using the some function I can do something like this:
customers.some(e => e.isEnabled == true)
So, now it will only return true if all the elements in the array have isEnabled property to true. Is that right?
Upvotes: 1
Views: 85
Reputation: 188
If you are using Underscore.js, You could use _.where() function.
_.where(customers, {isEnabled: true});
Upvotes: 0
Reputation: 4309
What you want is Array.prototype.some or Array.prototype.every
Here is how you'd use it in your case:
var customers = [
{ firstName: "John", isEnabled: true },
{ firstName: "Mary", isEnabled: false },
];
var goodCustomers = [
{ firstName: "George", isEnabled: true },
{ firstName: "Sandra", isEnabled: true },
];
function isNotEnabled(customer) {
return !customer.isEnabled;
}
function isEnabled(customer) {
return customer.isEnabled;
}
customers.some(isNotEnabled);
//=> true
goodCustomers.some(isNotEnabled);
//=> false
customers.every(isEnabled);
//=> false
goodCustomers.every(isEnabled);
//=> true
Functional libraries are also excellent for this kind of problem, here's a Ramda example just for fun:
R.all(R.prop("isEnabled"), customers);
//=> false
R.any(R.compose(R.not, R.prop("isEnabled")), customers);
//=> true
Upvotes: 3
Reputation: 92854
Use every
method:
customers.every(function(v){ return v.isEnabled; }); // will return true if every object 'is enabled'
Upvotes: 0