首页 > 解决方案 > 如果 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)
  }

标签: javascriptangulartypescript

解决方案


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

推荐阅读