Bryan
Bryan

Reputation: 3541

Iterate over each object In array

I have the following js code:

 $http.get($rootScope.appUrl + '/nao/system/getUserBox/' + $routeParams['id']).success(function(data) {
        $scope.userbox = data;
    });

$scope.userbox can contain one, or several objects. In this case, result for the user Is only one object:

 Object { mac="00:22:07:2A:8D:4B", type="ZAP100", serial="D15024H12B034568", more...}

The thing I want to do Is to print out Box for each OBJECT, not object property, In the array result.

I have tried like this:

<h5 class="bg-primary rmpad15" ng-repeat="userbox in userbox">Box</h5>

But this result In 19 rows of -elements, which Is for each object property, which Is wrong. If the array contains only one object, then I want ONE -element to be printed.

Upvotes: 2

Views: 68

Answers (2)

Sampson
Sampson

Reputation: 268344

You could test the return value for arrayness, and wrap it in an array if it is an object:

$scope.userbox = Array.isArray( data ) ? data : [ data ];

This approach should work in Internet Explorer 9 and newer. If, for whatever reason, you need support for Array.isArray in earlier versions of IE, you can polyfill it.

Upvotes: 2

Oskar Eriksson
Oskar Eriksson

Reputation: 2641

If you make sure the backend always returns the single or multiple objects in an array, you should be golden!

Upvotes: 0

Related Questions