Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return true if all objects in array has value in property

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
  }
});
like image 716
sch Avatar asked Mar 22 '16 07:03

sch


2 Answers

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;
like image 110
Tushar Avatar answered Oct 03 '22 14:10

Tushar


You could use the every() method:

var isTrue = objectArray.every(function(i) {
    return i.Value;
}
like image 32
cl3m Avatar answered Oct 03 '22 15:10

cl3m