如果数组中的所有对象在属性中都具有值,则返回true [英] return true if all objects in array has value in property
本文介绍了如果数组中的所有对象在属性中都具有值,则返回true的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个对象数组,像这样:
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}
]
如果此数组中的所有对象在属性值"中都有一个值,我想检查一下并返回true.
I would like to check, and return true, if all objects in this array has an value inside the property 'value'.
我认为我可以使用forEach循环来做到这一点,但是有没有比这更好的方法了?
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
}
});
推荐答案
只需使用 Array#every()
.
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);
将0
作为值进行测试的解决方案.
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);
这篇关于如果数组中的所有对象在属性中都具有值,则返回true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文