gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 18:52:35 24 4
gpt4 key购买 nike

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

[
{
"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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com