sch
sch

Reputation: 1388

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

Upvotes: 13

Views: 11876

Answers (3)

Tushar
Tushar

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

Nina Scholz
Nina Scholz

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

cl3m
cl3m

Reputation: 2801

You could use the every() method:

var isTrue = objectArray.every(function(i) {
    return i.Value;
}

Upvotes: 3

Related Questions