如何遍历这个 Json 对象(angularJS)

How do I loop through this Json object (angularJS)?

本文关键字:Json 对象 angularJS 遍历 何遍历      更新时间:2023-09-26

我正在尝试使用 AngularJS 遍历 Json 对象中的"选项卡"?我该怎么做?

var model = {
    "$id": "1",
    "tabs": [{
        "$id": "2",
        "id": 2,
        "name": "Output",
        "layoutId": 1,
        "order": 1,
        "dashboardId": 1
    }, {
        "$id": "15",
        "id": 3,
        "name": "Yield",
        "layoutId": 1,
        "order": 2,
        "dashboardId": 1
    }, {
        "$id": "24",
        "id": 4,
        "name": "Trend",
        "layoutId": 1,
        "order": 3,
        "dashboardId": 1
    }],
    "id": 1,
    "name": "Test",
    "title": "Test",
    "description": "Test Dashboard",
    "createDate": "2015-06-08T00:00:00+01:00",
    "ownerId": 1,
    "enabled": true
};

当我尝试此操作时,我在控制台中得到"未定义"。

angular.forEach(model.tabs, function (tab) {
    console.log(tab.name);
});

不知道我做错了什么?

编辑:数据来自 ASP.Net 控制器:

$http.get("/Dashboards/GetDashboardData").success(function (data) {
            model = data;
            angular.forEach(model.tabs, function (tab) {
                console.log(tab.name);
            });
        }).error(function (data) {
            console.log("error");
        });

我希望模型在您循环时尚未准备就绪。在检查器打开的情况下运行以下代码 - 您拥有的代码是正确的,但在您的情况下会失败,因为运行循环时model尚未准备就绪。

如果要异步加载数据,则需要等到返回数据,使用承诺或回调,然后循环通过它。

var model = {
    "tabs": [{
        "name": "Output",
    }, {
        "name": "Yield",
    }, {
        "name": "Trend",
    }],
};
angular.forEach(model.tabs, function (tab) {
    console.log(tab.name);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

好的,

我找到了答案。看起来我的控制器将 Json 对象作为字符串返回,因此我必须先将其切换到对象,然后才能将其用作对象。

在循环中使用模型之前,我已经添加了这一行:

model = JSON.parse(data);

有承诺的整个解决方案(不确定我现在是否需要它):

DataService.getDashboardData().then(function (data) {
        model = JSON.parse(data);
        angular.forEach(model.tabs, function (tab) {
            console.log(tab);
        });
    });
 app.service("DataService", ["$http", "$q", function ($http, $q) {
    return {
            getDashboardData: function () {
            var dfd = $q.defer();
                     $http.get('/Dashboards/GetDashboardData').success(function (result) {
                        dfd.resolve(result);
                });
            return dfd.promise;
        }
    };
}]);