javascript - 如何在 Angular 中检查数组中对象列表中的至少一个值是否为 true?

标签 javascript arrays angularjs

在我的网站中,我有一个数组,其中还包含另一个具有一些值的数组:

[
    {
        "name": "Pete",
        "place": "HOME",
        "houses": [
            {
                "key": "OFFICE",
                "value": false
            },
            {
                "key": "HOME",
                "value": true
            },
            {
                "key": "SHOP",
                "value": true
            }
        ]
    },
    {
        "name": "William",
        "place": "OFFICE",
        "houses": [
            {
                "key": "OFFICE",
                "value": false
            },
            {
                "key": "HOME",
                "value": false
            },
            {
                "key": "SHOP",
                "value": false
            }
        ]
    }
]

我可以很好地循环遍历两个对象,但我只想循环遍历houses(如果至少有housesvalue之一) > 是真的。因此,对于皮特,我想遍历房子,但对于威廉,我不想。我目前有这个代码:

<div ng-repeat="person in persons">
    {{ person.name }} in {{ person.place }} 
    <div ng-if="WHAT TO PUT HERE TO CHECK IF AT LEAST ONE OF THE VALUES IS TRUE??">
        has got the following houses: 
        <span ng-repeat="house in person.houses">
            <span ng-if="house.value">{{ house.key }} / </span>
        </span>
    </div>
</div>

但我不知道在 ng-if 中放入什么来检查任何 value 是否为 true。有人知道我应该如何解决这个问题吗?

最佳答案

给父对象分配flag,简单的实现就是这样

var people = [ /*your long array ommited*/ ];
angular.forEach(people, function(person){
    //checking length of (get house in person.houses where house.value === true)
    person.has_true_house = person.houses.some(function(item){
        return item.value === true;
    });
});

然后在你看来

<div ng-repeat="person in persons">
    {{ person.name }} in {{ person.place }} 
    <div ng-if="person.has_true_house">
        has got the following houses: 
        <span ng-repeat="house in person.houses">
            <span ng-if="house.value">{{ house.key }} / </span>
        </span>
    </div>
</div>

关于javascript - 如何在 Angular 中检查数组中对象列表中的至少一个值是否为 true?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34254573/

相关文章:

javascript - UWP 排除 WebView 控件的 "Microsoft C++ exception: Js::JavascriptException"异常

javascript - :hover only with mouse 的纯 css

javascript - 操作两个单独数组中的数组键值

c - 从函数返回 int 类型数组的问题

c++ - 无法找到二维数组中每一列的最大值

javascript - 如何在 AngularJS 中动态增加/减少段落元素的高度?

javascript - Angular : Pass variable to directive

Javascript 对象 - 过滤时,我的对象的键变成有序数字列表

javascript - 获取数组 Angular 的单个属性

javascript - 如何将阅读更多 - 阅读更少按钮始终放在段落末尾?