You need first to loop through JSON to create an Array of the locations by removing duplicates. And then loop again locations to create collapsibles. While looping through locations, go through JSON to extract Sub locations and append them to there parents.
I've added class of location's name for each collapsible to facilitate appending Sub locations.
/* add all locations from JSON */
var collapsible = [];
/* remove duplicate locations */
var locations = [];
$.each(data, function (i, v) {
collapsible.push(v.webform_views_add_sublocation_form_location);
$.each(collapsible, function (i, v) {
if ($.inArray(v, locations) === -1) {
locations.push(v); /* ["location1", "locations"] */
}
});
});
/* loop through locations */
$.each(locations, function (i, loc) {
var parent = loc;
var elements = '';
/* loop through JSON */
$.each(data, function (x, sub) {
var subLoc = sub.webform_views_add_sublocation_form_sub_location;
if (sub.webform_views_add_sublocation_form_location == parent) {
/* sub locations */
elements += '<li><a href="#">' + subLoc + '</a></li>';
}
});
/* create collapsibles based on number of locations
add listview, append sub locations and refresh
collapsible-set at once */
$("#location-list").append($("<div/>", {
"data-role": "collapsible",
"class": parent
}).append($("<h3/>").text(parent)).append($("<ul/>", {
"data-role": "listview",
"data-theme": "b"
}).append(elements).listview())).collapsibleset('refresh');
});