Currently working on a JavaScript project that involves pulling in multiple JSON files to use in graphs. The challenge is identifying when the end of an associative array has been reached within a loop using $.each()
(jQuery) so that the next JSON file can be triggered. I've come across solutions for single-tiered objects, but what about multi-tiered objects? How can the last element know it's the final one?
For example, here's a snippet of the JSON data I am dealing with:
{
"Network":{
"Hardware":262464,
"Software":53016,
"Internal Personnel":440202,
"External Personnel":188658,
"Outside Services":1344100,
"Facilities and Overhead":16172,
"Other":92588,
"Total":2397200
},
"Wide Area Network":{
"Hardware":75600,
"Software":18900,
"Internal Personnel":132300,
"External Personnel":56700,
"Outside Services":315000,
"Facilities and Overhead":6300,
"Other":25200,
"Total":630000
}
}
Below is a simplified version of the loop structure used to process this JSON data:
function buildColumns(array, parent) {
$.each(array, function(key, value) {
var newParent = $('<column>');
$('<columnBox>').append($('<h2>').html(key)).append(newParent).appendTo(parent);
if(value instanceof Object) buildColumns(value, newParent);
});
}
The loop above functions in a pseudo-recursive manner, although its final implementation may vary. Stay tuned!