在这里,我想从第一页的Json数据访问顶级市场细节,但我无法访问子级市场细节。我想在下一页显示子级市场名称。
$scope.myData = {
"market": [{
"mid": 3,
"mname": "mark1",
"submarket": [{
"id": 20,
"name": "val1"
}, {
"id": 24,
"name": "val2",
"submarket": [{
"id": 26,
"name": "val21"
}]
}]
"market": [{
"mid": 4,
"name": "mark1.1",
"submarket": [{....
}]
}]
}, {
"mid": 6,
"mname": "mark2",
}]
};
$scope.markname = []; /*stores top level markets*/
angular.forEach($scope.myData.market, function(org) {
$scope.markname.push(org)
}) /*works fine and has the details of market (mid:3 and mid:6)*/
$scope.submark = [];
angular.forEach($scope.markname.submarket, function(sorg) {
$scope.submark.push(sorg)
}) /*doesn't store anything*/
答案 0 :(得分:1)
应该是:
$scope.submark = [];
angular.forEach($scope.markname, function(sorg) {
angular.forEach(sorg.submarket, function(subsorg) {
$scope.submark.push(subsorg)
});
});
答案 1 :(得分:1)
$scope.markname
是一个数组,您在第一个forEach
上将项目推送到该数组中,但是在第二个尝试访问该属性submarket
时。这在markname
数组中不存在,它存在于数组中的每个项目上。
我已经使用本地forEach
完成了我的示例,根本不需要角度来处理这里,它也隐藏了未定义的问题,因为本机可用于数组原型,如果你尝试它会引发异常将undefined
称为undefined
,而棱角分享快乐地接受markname.forEach(function(sorg) {
if (sorg.hasOwnProperty('submarket')) {
submark.push(sorg.submarket);
}
});
并继续。
所以一个简单的修复就是
submark.push.apply(submark, sorg.submarket);
请参阅小提琴:https://jsfiddle.net/0y6r0mw1/
编辑:值得注意的是,这将生成一个多维数组,如果不需要,你可以将它们连在一起,例如:
{{1}}
答案 2 :(得分:0)
您共享的json数据不正确。请仔细阅读demo。
<强> HTML:强>
<div ng-app="app" ng-controller="test">
</div>
<强> JS:强>
var app = angular.module('app', []);
app.controller('test', function ($scope) {
$scope.myData = {
"market": [{
"mid": 3,
"mname": "mark1",
"submarket": [{
"id": 20,
"name": "val1"
}, {
"id": 24,
"name": "val2",
"submarket": [{
"id": 26,
"name": "val21"
}]
}, {
"mid": 4,
"name": "mark1.1",
"submarket": [{
"id": 27,
"name": "val221"
}]
}]
}, {
"mid": 6,
"mname": "mark2",
}]
};
$scope.markname = []; /*stores top level markets*/
angular.forEach($scope.myData.market, function (org) {
$scope.markname.push(org)
}) /*works fine and has the details of market (mid:3 and mid:6)*/
console.log('markname', $scope.markname);
$scope.submark = [];
angular.forEach($scope.markname, function (sorg) {
angular.forEach(sorg.submarket, function (subM) {
$scope.submark.push(subM)
})
})
console.log('submark', $scope.submark);
});
答案 3 :(得分:0)
function iterate(obj) {
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
if (typeof obj[property] == "object") {
iterate(obj[property]);
}
else {
console.log(property + " " + obj[property]);
}
}
}
}
iterate(object)