Home > Back-end >  Check array length in object javascript
Check array length in object javascript

Time:09-30

I have some object like this

    const array = 
    {
      "entities": [
        {
          "annexes": [
            {
              "buildingUniqueIds": []
            },
            {
              "buildingUniqueIds": []
            },
            {
              "buildingUniqueIds": []
            },
          ],
          "buildingUniqueIds": []
        }
      ]
}

I need to check if any of those array is empty to return true, is this possible to do in one iteration, here is what I have tried for now, but some does not check array length it always return true even if array is empty :(

  get haveBuildingUniqueIds(): boolean {
    const condition1 = this.array.entities.some(x => x.annexes.some(y => y.buildingUniqueIds.some));
    const condition2 = this.array.entities.some(x => x.buildingUniqueIds.some);
    return condition1 && condition2;
  }

CodePudding user response:

some is the right method to use, but it's a method, not a flag, so your innermost .some(y => y.buildingUniqueIds.some) will always return true, because a method is a truthy value.

Instead, check length:

const hasEmpties = array.entities.some(({annexes, buildingUniqueIds}) =>
    buildingUniqueIds.length === 0 ||
    annexes.some(({buildingUniqueIds}) => buildingUniqueIds.length === 0)
);

Live Example:

Side note: If you like, you can use !buildingUniqueIds.length rather than buildingUniqueIds.length === 0.

Or without destructuring if you prefer:

const hasEmpties = array.entities.some(entity =>
    entity.buildingUniqueIds.length === 0 ||
    entity.annexes.some(annex => annex.buildingUniqueIds.length === 0)
);

Live Example:

  • Related