Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Use javascript to assign an example of a johnson array depth


May 08, 2021 JSON


Table of contents


Use javascript to assign depth to a johnson array

The code looks like this:

<!DOCTYPE HTML> 
<html> 
<head> 
<title>test1</title> 
</head> 
<body> 
<script> 
var arr={ 
"name":"zhansan", 
"age":23, 
"address":{ 
"city":"beijing", 
"gas":{ 
"gasSheet":"气态流出物月报", 
"H_adjust":1 
}, 
"time":{ 
"duration":31 
} 
}, 
"units":{"title":"function"} 
} 
function show(obj){ 
var tmp={}; 
for(var i in obj){ 
if(obj[i]=="object"){ 
<span style="color:#ff0000;">tmp[i]=show(obj[i]);</span> 
} 
else{ 
<span style="color:#ff0000;">tmp[i]=obj[i]</span> 
} 
} 
return tmp; 
} 

var result=show(arr); 
console.log(result);
</script> 
</body> 
</html>
</pre><p></p><p>利用递归思想,其中注意赋值语句</p><p>可用于不同的环境</p><p></p><pre>

How to assign a jSON object to a jSON array

Let's say that the jSON object is var kpis, s."A": s.1,2,3,4,5,""b":"2,3,4,5,6', jSON array is var series.

The first method:

[javascript] view plain copy
var index=0;  
for( var tests in kpis){   
     series[index].name=tests;   
     series[index].data=kpis[tests];  
}

Comment: The first method is not applicable in cases where there are more than two name/value pairs, and you can only manually increase the length of the jSON array, which is cumbersome. Guided by boss, there is a second approach.


The second method:

[html] view plain copy
series=[];  
for(var tests in kpis){  
     //定义一个新的jSON对象,改变成jSON数组中jSON数据的格式  
     var json = {name:tests, data:kpis[tests]};  
     //通过数组的push()方法向数组中增加jSON数据  
     series.push(json);  
} 

Comment: The second method, when traversing the kpis this jSON object, generates a new format of the jSON object, constantly pushing into the array, so that the purpose is achieved, and even with a name/value pair is not afraid, the versatility is enhanced.

So the second method is recommended.