javascript - 如果 OF 元素中组的长度大于零,则检查对象数组
问题描述
我有一个对象数组。在这个对象中,我有一组确定数量的组。
如果在 OF 元素等于 12.2 的情况下组大于零,则有一种方法可以在对象数组中检查。
我试过的
Sort = [
{
id: 1,
of: 12.2,
tam: 's',
name: 'Color Run',
groups: [
{
type: 'type1',
quant: 21
}
]
},
{
id: 2,
of: 12.2,
tam: 'M',
name: 'Color Run',
groups: []
},
{
id: 3,
of: 2.2,
tam: 'L',
name: 'Works',
groups: []
}
];
ngOnInit() {
console.log(this.Sort)
var x = this.Sort.forEach(element => {
if(element.of == 12.2){
if(element.groups.length > 0){
return true;
}
else{
return false;
}
}
});
console.log(x)
}
解决方案
forEach
忽略返回值并对所有元素执行。因此,使用some()
(此处的文档)会更容易且性能更高,例如
const exists = this.Sort.some(s => s.of === 12.2 && s.groups.length > 0);
如果你想使用 forEach ,你可以将你的布尔值放在循环之外,初始值为false
,然后仅当元素存在时才将其值设置为 true ,例如
let exists = false;
this.Sort.forEach(e => {
if (e.of === 12.2 && e.groups.length > 0) {
exists = true;
}
});
推荐阅读
- mongodb - 用于海量数据的 MongoDB
- c++ - C++ 语法解释中的赋值运算符重载
- javascript - 回调被多次触发,我不知道为什么
- python - pip 已安装模块但 python 给出导入错误
- java - java opencv Features2d.drawMatches - 断言失败或 NullPointerException
- javascript - PHP 和 Vue 集成
- hibernate - Hibernate 映射一个 Map (HashMap) 总是添加新行而不是更新
- javascript - 动态更改关键帧后如何重新启动更新的动画?
- java - 如何管理新标签
- oracle - 如何知道oracle 11g xe的端口号