I am retrieving data via JSON from a database, so the data is subject to change constantly; I can't hard-code the JSON. Here is some sample JSON to illustrate this example:
[{"Building":"18A","Room":219,"Location":"E-4-6","BarCode":"P000019152"},
{"Building":"18G","Room":"112HALL","Location":"J-8-5","BarCode":"P000031111"},
{"Building":"18G","Room":"112HALL","Location":"J-8-5","BarCode":"P166279435"},
{"Building":"18G","Room":"112HALL","Location":"A-10-7","BarCode":"P352831849"},
{"Building":"18G","Room":"5P04","Location":"C-4-10","BarCode":"P726526379"},
{"Building":"18C","Room":"6THST","Location":"CAGE14","BarCode":"P000453262"},
{"Building":"18C","Room":"6THST","Location":"CAGE13","BarCode":"P954732810"}]
What I need to do is parse this array and create a tree view out of it. From above, the tree view would look like this:
>18A
>219
>E-4-6
>P000019152
>18G
>112HALL
>J-8-5
>P000019152
>P166279435
>A-10-7
>P166279435
>5P04
>C-4-10
>P726526379
>18C
>6THST
>CAGE14
>P000453262
>CAGE13
>P954732810
The important thing to note is my JSON is not structured in a way that there are parent and child objects; in other words, it is not nested. Is there any way I can parse this JSON string and create a logical and hierarchical tree view out of it, based on the order of building, room, location, then bar code?
What I've tried so far:
var input=[{"Building":"18A","Room":"219","Location":"E-4-6","BarCode":"P000019152"},
{"Building":"18G","Room":"112HALL","Location":"J-8-5","BarCode":"P000031111"},
{"Building":"18G","Room":"112HALL","Location":"J-8-5","BarCode":"P166279435"},
{"Building":"18G","Room":"112HALL","Location":"A-10-7","BarCode":"P352831849"},
{"Building":"18G","Room":"5P04","Location":"C-4-10","BarCode":"P726526379"},
{"Building":"18C","Room":"6THST","Location":"CAGE14","BarCode":"P000453262"},
{"Building":"18C","Room":"6THST","Location":"C1","BarCode":"P954732810"}];
function ToNestedObject(input){
var i, y, len = input.length, parts, partsLen, obj = {}, prev;
for(i = 0; i < len; i++){
parts = input[i];
partsLen = parts.length;
prev = obj;
for(y = 0; y < partsLen; y++){
prev[parts[y]] = prev[parts[y]] || {};
prev = prev[parts[y]];
}
if(!prev.ids){
prev.ids = [];
}
prev.ids.push(input[i].id);
}
return obj;
}
function ToHTML(input){
var html = '<ul>';
for(var key in input){
if(input[key] instanceof Array){
for(var i = 0; i < input[key].length; i++){
html += '<li>' + input[key][i] + '</li>';
}
} else {
html += '<li>' + key + ToHTML(input[key]) + '</li>';
}
}
html += '</ul>';
return html;
}
document.getElementById('test').innerHTML = ToHTML(ToNestedObject(input));
ulelements, this is very simple to do. What difficulty are you having doing this yourself?