<分区>
我做了一个小脚本,迭代并打印一个JSON对象的值,如果对象的值是另一个对象或数组,就会调用这个工作来迭代值(数组或对象) .
这是我在打印数组的值时出现的问题,打印的值也在 __ proto__ 中添加值,就像数组的一部分
请注意,您需要有一个 <ul>
HTML 中 ID 为 jsonUls
的元素让这段代码工作。
代码:
var json = '{"jsonObject":{"value1":"value2", "array1" : ["value1","value2","value3"]}}'; /* Create Json */
var element = $('#jsonUls');
var object = JSON.parse(json); /* Create object */
/* call the function*/
recursivePrintObjectValues(object, element);
function recursivePrintObjectValues(object, element) {
for(key in object) { /* Iterate the object */
var value = object[key]; /*Get the object value */
/* Verify if value is of type object or an array */
if(typeof value === 'object' || Array.isArray(value)){
/*Generate random */
var random = new Date().valueOf() * Math.random() + 351;
/* Append Li with key */
appendLi(key, '', element);
/*Append UL and get the selector*/
var ul = appendUl(random, element);
/*Call the function with the object and the selector to append (to iterate childs of this object)*/
recursivePrintObjectValues(value, ul);
} else {
appendLi(key, value, element);
}
}
}
function appendUl(random, element) {
var ul = $('<ul></ul>', {
id: random
})
ul.appendTo(element);
return ul;
}
function appendLi(key, value, element) {
if(value == '[object Object]') {
value = '';
}
$('<li></li>', {
text: key + ' : '+ value
}).appendTo(element);
}
结果如下,我不知道为什么以及如何避免它,希望任何人都可以解释我。
<pre>
<ul id="jsonUls">
<li>jsonObject : </li>
<ul id="448773395479.7797">
<li>value1 : value2</li>
<li>array1 : </li>
<ul id="295240780591.31195">
<li>0 : value1</li>
<li>1 : value2</li>
<li>2 : value3</li>
<li>$pnmap$ : function $$JSCompiler_prototypeAlias$$$$pnmap$$($f$$30$$,$opt_obj$$28$$){return $goog$array$map$$.apply($JSCompiler_alias_NULL$$,$pn$aargs_$$(this,arguments))}</li>
<li>$pnforEach$ : function $$JSCompiler_prototypeAlias$$$$pnforEach$$($f$$32$$,$opt_obj$$30$$){$goog$array$forEach$$.apply($JSCompiler_alias_NULL$$,$pn$aargs_$$(this,arguments));return this}</li>
<li>$pnequals$ : function $$JSCompiler_prototypeAlias$$$$pnequals$$($arr2$$13$$,$opt_equalsFn$$2$$){return $goog$array$equals$$.apply($JSCompiler_alias_NULL$$,$pn$aargs_$$(this,arguments))}</li>
<li>$pnfindIndex$ : function $$JSCompiler_prototypeAlias$$$$pnfindIndex$$($f$$41$$,$opt_obj$$43$$){return $goog$array$findIndex$$.apply($JSCompiler_alias_NULL$$,$pn$aargs_$$(this,arguments))}</li>
<li>$pnindexOf$ : function $$JSCompiler_prototypeAlias$$$$pnindexOf$$($obj$$76$$,$opt_fromIndex$$10$$){return $goog$array$indexOf$$.apply($JSCompiler_alias_NULL$$,$pn$aargs_$$(this,arguments))}</li>
</ul>
</ul>
</ul>
</pre>