遍历数组中的每个对象

时间:2022-02-24 13:00:25

I have the following js code:

我有以下js代码:

 $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:

美元的范围。userbox可以包含一个或多个对象。在这种情况下,用户的结果只有一个对象:

 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.

但是这会导致19行-元素,每个对象属性都是-元素,这是错误的。如果数组只包含一个对象,那么我希望打印一个-元素。

2 个解决方案

#1


2  

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

您可以测试arrayness的返回值,如果它是一个对象,可以将它封装在一个数组中:

$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.

这种方法应该在Internet Explorer 9和更新版本中使用。无论出于什么原因,如果需要对数组的支持。isArray在IE的早期版本中,可以对其进行多填充。

#2


0  

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

如果确保后端总是返回数组中的单个或多个对象,那么您应该是黄金的!

#1


2  

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

您可以测试arrayness的返回值,如果它是一个对象,可以将它封装在一个数组中:

$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.

这种方法应该在Internet Explorer 9和更新版本中使用。无论出于什么原因,如果需要对数组的支持。isArray在IE的早期版本中,可以对其进行多填充。

#2


0  

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

如果确保后端总是返回数组中的单个或多个对象,那么您应该是黄金的!