OK guys need some help out there. I\'m still learning Javascript and its interactions JSON. I have a a JSON like this
[{
\"categories\":\"Food\",
\"subca
I gave this a shot and might as well post my results. The data doesn't line up perfectly with what you have. It doesn't require jQuery, and it can be used to sort data multiple times.
Object.prototype.groupBy = function(itemName, preGrouped)
{
if(preGrouped)
{
for(prop in this)
{
if(typeof(this[prop]) === 'object' && this[prop].groupBy !== undefined)
{
var reGroup = this[prop].groupBy(itemName);
this[prop] = reGroup;
}
}
return this;
}
else
{
var uniqueItems = {};
var uniqueItemLength = 0;
for(var i=0, length=this.length; i < length; i++)
{
var item = this[i];
var z =0;
var found = false;
while(z < uniqueItemLength)
{
if(item[itemName] in uniqueItems)
{
uniqueItems[item[itemName]].push(item);
found = true;
break;
}
z++;
}
if(!found)
{
uniqueItems[item[itemName]] = [];
uniqueItems[item[itemName]].push(item);
uniqueItemLength++;
}
}
return uniqueItems;
}
}
It gets called by:
var convertedData = oldJSON.groupBy('categories').groupBy('subcategories', true)
Beterraba's answer is correct. I put some time in this one and figured I'd at least post. Maybe it would help someone else.
http://jsfiddle.net/8VRuy/