zomdar
zomdar

Reputation: 273

how to find a if an array is empty within an array in javascript (angularjs)

I'm currently trying to find if an object property "itemBag" is set in an object.

The issue I am having is that I am getting 2 different arrays from the api and the property "itemBag" is not included within the object so I get an "undefined" error.

The 2 different arrays that I get:

Array 1:

[
  [
    {
      "orderNumber": 1,
      "itemBag": [
        {
          "size": 10000,
          "name": "hello.pdf",
        }
      ]
    }
  ]
]

Array 2:

[
  [
    {
      "orderNumber": 1
    }
  ]
]

The function that I am using to try to determine if "itemBag" is empty or not:

$scope.reproductions is the array mentioned above

$scope.checkFirstDesignContainerIsEmpty = function() {
    var containerIsEmpty;
    if($scope.reproductions[0][0].includes(itemBag)) {
      containerIsEmpty = true;
    }
    return containerIsEmpty;
};

I keep getting an error that itemBag is undefined.

Upvotes: 0

Views: 42

Answers (2)

Drew Reese
Drew Reese

Reputation: 202667

What is itemBag in your function? It isn't declared before use so of course it is undefined. $scope.reproductions[0][0] is also not an array, it is an object, so trying to call array functions like includes just won't work.

$scope.checkFirstDesignContainerIsEmpty = function() {
    var containerIsEmpty;
    if($scope.reproductions[0][0].includes(itemBag)) { // itemBag hasn't been declared, so is undefined
      containerIsEmpty = true;
    }
    return containerIsEmpty;
};

To test if the $scope.reproductions[0][0] object doesn't have an itemBag property, or if it does and it is empty:

$scope.checkFirstDesignContainerIsEmpty = function() {
    var containerIsEmpty = true;

    // test if itemBag key exists and value has truthy length value
    const { itemBag } = $scope.reproductions[0][0];
    if(itemBag && itemBag.length) {
      containerIsEmpty = false;
    }
    return containerIsEmpty;
};

Or more succinctly:

$scope.checkFirstDesignContainerIsEmpty = function() {
    const { itemBag } = $scope.reproductions[0][0];
    return !(itemBag && itemBag.length);
};

Upvotes: 2

Austin Gordon
Austin Gordon

Reputation: 69

Try adding quotes around itemBag:

$scope.checkFirstDesignContainerIsEmpty = function() {
  var containerIsEmpty;
  if($scope.reproductions[0][0].includes('itemBag')) { // Added quotes here
    containerIsEmpty = true;
  }
  return containerIsEmpty;
};

Upvotes: -1

Related Questions