简体   繁体   中英

How to compare all nested child elements length with each other?

I have 1 object which contains nested child like below:

$scope.artists.materials.items[] //contains list of items

Now I would have several artist which will contains list of items but in this I want to check total length of each item of artists and if mismatch found then I want to return true or false.

For eg : I have 2 artist and from this Artist1 contains 2 items and Artist2 contains only 1 item then this is a mismatch as I want to have both the artist to contains same number of items.

But here I am confused with how do i do all this comparison in AngularJS way.

Code:

 function checkItemsValidity() {
        angular.forEach($scope.artists, function (artist) {
            alert(artist.materials.items.length);
        });
    }

How can I do this in better way?

If all artists have to have the same number of items , then just store the length of the items from the first artist and make sure all of them have that same items length. Something like:

Updated with suggestions from comments

function checkItemsValidity() {
    var itemsLength = $scope.artists[0].materials.items.length;
    angular.forEach($scope.artists, function (artist) {
        if(artist.materials.items.length != itemsLength) {
            return false;
        }
    });
    return true;
}

An improvement to Lex's answer: no need for the isValid variable, if there's no reason to go through the rest once the first difference is found.

function checkItemsValidity() {
  var len = $scope.artists[0].materials.items.length;
  for (var i = 0; i < $scope.artists.length; i++) {
    if ($scope.artists[i].materials.items.length != len) {
      return false;
    }
  }
  return true;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM