VIDEO
this script will create table of max length of array fields in test.txt json file.
< html >
< head >
< script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js " > </ script >
< script >
var d1;
var mt = {} ;
var md = {} ;
$ (function () {
$.getJSON ('/test.txt' , function (data ) {
d1=data;
for (let i = 0; i < d1.length; i++ ) {
let ob=d1 [ i ] ;
for (prop in ob ) {
if (!mt [ prop ] ){
mt [ prop ] = 0;
md [ prop ] = "" ;
}
if (mt [ prop ] < ob [ prop ] .length ){
let s=ob [ prop ] ;
mt [ prop ] = s.length;
md [ prop ] = s;
}
}
}
for (prop in mt ) {
var tblRow = "<tr>" + "<td>" + prop + "</td>" +
"<td>" + mt [ prop ] + "</td>" + "<td>" + md [ prop ] + "</td>" + "</tr>"
$ (tblRow ).appendTo ("#userdata tbody" );
}
} );
} );
</ script >
</ head >
< body >
< div class = "wrapper" >
< div class = "profile" >
< table id = "userdata" border = "2" >
< thead >
< th > field name </ th >
< th > max length</ th >
< th > example</ th >
</ thead >
< tbody >
</ tbody >
</ table >
</ div >
</ div >
</ body >
</ html >
you can install LiveServer VsCode plugin in order to get this html working
also I would change internal code a little to accommodate digital values and possible nulls and -1 to indicate field doesn't have value , here is my script
< script >
var d1;
var mt = {} ;
var md = {} ;
$ (function () {
$.getJSON ('/nutrition.txt' , function (data ) {
d1=data.nutrition;
console.log ("loaded" +d1.length );
for (let i = 0 ; i < d1.length; i++ ) {
let ob=d1 [ i ] ;
for (prop in ob ) {
if (!mt [ prop ] ){
mt [ prop ] =-1;
md [ prop ] = "" ;
}
if (!ob [ prop ] ) continue ;
if (mt [ prop ] < ("" +ob [ prop ] ).length ){
let s= "" +ob [ prop ] ;
mt [ prop ] = s.length;
md [ prop ] = s;
}
}
}
for (prop in mt ) {
var tblRow = "<tr>" + "<td>" + prop + "</td>" +
"<td>" + mt [ prop ] + "</td>" + "<td>" + md [ prop ] + "</td>" + "</tr>"
$ (tblRow ).appendTo ("#userdata tbody" );
}
} );
} );
</ script >
No comments:
Post a Comment