我想通过跟随json迭代并创建一个动态表单。但是,它的关键和价值都不相同。那么如何在JS中迭代它?
["register_form",
{
"name":{
"fielde":"textfield",
"description":""
},
"pass":{
"pass1":{
"field":"password"
},
"pass2":{
"field_type":"password"
}
},
"mail":{
"field":"textfield",
"description":""
},
"field_first_name":{
"field_type":"textfield",
"description":""
}
}
]

这些都不起作用:
//Get the size of object = no. of fileds to be created
var size = Object.keys(response[1]).length;
console.log("Size..." + size);
console.log("Keys.." + Object.keys(response[1]));
var keys = [];
var model = [];
var label = [];
keys.push(Object.keys(response[1]));
for(var i=0;i<keys.length;i++) {
angular.forEach(response[1].keys[i], function(key, value){
console.log(key + "..." + value);
});
&#13;
答案 0 :(得分:1)
答案 1 :(得分:1)
试试这个
var jimApp = angular.module("mainApp", []);
jimApp.controller('mainCtrl', function($scope, $sce){
$scope.user = {};
$scope.register_form = {"name":{
"field_type":"text",
"description":""
},
"pass1":{
"field_type":"password"
},
"pass2":{
"field_type":"password"
},
"mail":{
"field_type":"text",
"description":""
},
"field_first_name":{
"field_type":"text",
"description":""
} };
$scope.formData = { name : "" };
$scope.html = "";
angular.forEach($scope.register_form, function(value, key){
$scope.html = $scope.html + "<input type="+ value.field_type +" placeholder="+key+" >";
});
$scope.trustedHtml = $sce.trustAsHtml($scope.html);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="mainApp" ng-controller="mainCtrl">
<form>
<div ng-bind-html="trustedHtml">
</div>
</form>
</div>
答案 2 :(得分:0)
<强>更新强>
我认为这就是你所需要的。您可以根据需要格式化输出。
var data = {
"name":{
"fielde":"textfield",
"description":""
},
"pass":{
"pass1":{
"field":"password"
},
"pass2":{
"field_type":"password"
}
},
"mail":{
"field":"textfield",
"description":""
},
"field_first_name":{
"field_type":"textfield",
"description":""
}
};
function toArray(obj) {
var result = [];var passName;var tempArray = [];
for (var prop in obj) {
var value = obj[prop];
if (typeof value === 'object') {
$('#myForm').append("<br/><b>[[" + prop +"]]</b><br/>");
if ($.isNumeric(prop)) {
passName = name + "[" + prop + "]";
} else {
passName = name + "['" + prop + "']";
}
tempArray = toArray(value, passName);
$.each(tempArray, function (key, value) {
result.push(value);
});
} else {
$('#myForm').append("<label>" + prop +"</label> : <span>" + obj[prop] + "</span><br/>");
result.push(name + "['" + prop + "']");
}
}
return result;
}
toArray(data);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myForm">
</div>
&#13;