this fiddle groups them by name. Use CTRL + J in chrome to see the console output of the grouped JSON
$.each(array, function (i, item) { // iterate your JSON array
var foundItem = false; // track if an item exists in your new array
$.each(separateArray, function (y, newItem) { // iterate your new array
if (newItem.name == item.name) { // if there is an item with the same name
if (!(newItem.url instanceof Array)) { // check if the url is an array
newItem.url = [newItem.url]; // if not, then make it an array
}
newItem.url.push(item.url); // push the url as an array
foundItem = true; // notify that the item is found and we dont have to add it
}
});
if (!foundItem) { // if no item is found
separateArray.push(item); // push this item into our new array
}
});
I personally like to use knockout for binding data to the view. Here is what I did using knockout
I put the $.getJson
into the viewModel
that way, when knockout initialises it will fire the ajax request and then populate the binded array.
var viewModel = function () {
var self = this;
self.displayArray = ko.observableArray([]);
$.getJSON("/echo/json/",function(json){
// here obviously you put json through that groupJson function
self.displayArray(groupJson());
});
}
This way there is no need to try and build up the html display yourself, and predict what its going to look like when the page has fully rendered. Knockout will create HTML items where needed (if you have used a foreach for example).
This way you can still see the design of your page in HTML and how it will fit in with the rest.