Reputation: 1388
I have an array of objects, something like this:
$scope.objectArray = [
{Title: 'object1', Description: 'lorem', Value: 57},
{Title: 'object2', Description: 'ipsum', Value: 32},
{Title: 'object3', Description: 'dolor', Value: 135}
]
I would like to check, and return true, if all objects in this array has an value inside the property 'value'.
I think I could do it with an forEach loop, but is there a better way than this?
var isTrue = true;
angular.forEach(objectArray, function(o){
if (!o.Value){
isTrue = false; // change variable 'isTrue' to false if no value
}
});
Upvotes: 13
Views: 11876
Reputation: 87203
You can use Array#every
with Arrow function
var isTrue = objectArray.every(obj => obj.Value);
var objectArray = [
{Title: 'object1', Description: 'lorem', Value: 57},
{Title: 'object2', Description: 'ipsum', Value: 32},
{Title: 'object3', Description: 'dolor', Value: 135}
];
var isTrue = objectArray.every(obj => obj.Value);
document.body.innerHTML = isTrue;
Update:
To handle 0
value, Object#hasOwnProperty
can be used.
objectArray.every(obj => obj.hasOwnProperty('Value'))
var objectArray = [
{Title: 'object1', Description: 'lorem', Value: 57},
{Title: 'object2', Description: 'ipsum', Value: 32},
{Title: 'object3', Description: 'dolor', Value: 0}
];
var isTrue = objectArray.every(obj => obj.hasOwnProperty('Value'));
document.body.innerHTML = isTrue;
Upvotes: 20
Reputation: 386654
Just use Array#every()
, if 0
does not count.
var $scope = { objectArray: [{ Title: 'object1', Description: 'lorem', Value: 57 }, { Title: 'object2', Description: 'ipsum', Value: 32 }, { Title: 'object3', Description: 'dolor', Value: 135 }] },
isTrue = $scope.objectArray.every(function (a) {
return a.Value;
});
document.write(isTrue);
Solution with test for 0
as a value.
var $scope = { objectArray: [{ Title: 'object1', Description: 'lorem', Value: 0 }, { Title: 'object2', Description: 'ipsum', Value: 32 }, { Title: 'object3', Description: 'dolor', Value: 135 }] },
isTrue = $scope.objectArray.every(function (a) {
return a.Value || a.Value === 0;
});
document.write(isTrue);
Upvotes: 3
Reputation: 2801
You could use the every()
method:
var isTrue = objectArray.every(function(i) {
return i.Value;
}
Upvotes: 3