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
}
});
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;
You could use the every()
method:
var isTrue = objectArray.every(function(i) {
return i.Value;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With