如何以树格式打印此动态Json数组 我期望的输出是这样的
firstname :- test
Last name :-test1
Account=>
role :-test3
status:test4
Account1=>
role:-
status:-
JSON
$scope.inputs = [
{
"firstname" : "Test"
},{
"lastname" : "Test1"
},{
"Account" : [
{"role" : "Test3"},
{"status" : "Test4"},
]
},
{
"Account1" : [
{"role" : "Test3"},
{"status" : "Test4"},
]
},
{
"Account2" : [
{"role" : {
'dim3': {
'dim4':{
'dim5':'cccc'
}
}
}
},
{"status" : "Test4"},
{"status" : "Test4"},
]
},
{
"ending" : "yes"
}
];
答案 0 :(得分:1)
您可以将每个对象的第一个键属性和值分配给一个对象,如
$scope.inputs.forEach(function(data){
obj[Object.keys(data)[0]] = data[Object.keys(data)[0]]
});
angular.module("app",[])
.controller("ctrl",function($scope){
$scope.inputs = [
{
"firstname" : "Test"
},{
"lastname" : "Test1"
},{
"Account" : [
{"role" : "Test3"},
{"status" : "Test4"},
]
},
{
"Account1" : [
{"role" : "Test3"},
{"status" : "Test4"},
]
},
{
"Account2" : [
{"role" : {
'dim3': {
'dim4':{
'dim5':'cccc'
}
}
}
},
{"status" : "Test4"},
{"status" : "Test4"},
]
},
{
"ending" : "yes"
}
];
var obj= {};
$scope.inputs.forEach(function(data){
obj[Object.keys(data)[0]] = data[Object.keys(data)[0]]
});
//var arr = $scope.inputs.map(o=> o);
console.log(obj)
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
</div>
答案 1 :(得分:1)
您可以通过在模板中递归地包含另一个模板来执行此操作,该模板会对对象中的每个值进行不同的渲染,具体取决于它仍然是对象。 函数isArrayOrObject用于检查值是否为对象
//index.html:
<body ng-app="mainApp">
<div ng-controller="controller">
<ul>
<li ng-repeat="(key, value) in inputs" ng-include="'node_renderer.html'"></li>
</ul>
</div>
</body>
//node_renderer.html: a template to be included that render each value in the object:
<div ng-switch="isArrayOrObject(value)">
<div ng-switch-when="false">{{key}}: {{value}}</div>
<div ng-switch-when="true">
<span>{{key}}=></span>
<ul>
<li ng-repeat="(key, value) in value" ng-include="'node_renderer.html'"></li>
</ul>
</div>
</div>
app.controller('controller', function($scope) {
$scope.isArrayOrObject = function(value) {
return angular.isObject(value);
};
$scope.inputs = [
{
"firstname" : "Test"
},{
"lastname" : "Test1"
},{
"Account" : [
{"role" : "Test3"},
{"status" : "Test4"},
]
},
{
"Account1" : [
{"role" : "Test3"},
{"status" : "Test4"},
]
},
{
"Account2" : [
{"role" : {
'dim3': {
'dim4':{
'dim5':'cccc'
}
}
}
},
{"status" : "Test4"},
{"status" : "Test4"},
]
},
{
"ending" : "yes"
}
];
});