This is really not a question. I was looking up this solution but couldn't find it anywhere. Thought of posting it here so it may save someone's time.
Here was my issue: I had a JSON coming from server which was not nested. Lets take example of Movies:
var movies = [
{"name":"Ice Age 3", "language":"English", "year":"2012"},
{"name":"Ice Age 3", "language":"French", "year":"2011"},
{"name":"Ice Age 3", "language":"German", "year":"2013"}
];
Now effectively speaking, there is no need for server to return it like this, however this was my case and since I was using jquery-template I wanted to have it as a nested JSON object. Something like this:
var movies = [{
"name": "Ice Age 3",
"details": [
{"language": "English", "year": "2012"},
{"language": "French", "year": "2011"},
{"language": "German", "year": "2013"}
]
}];
Here is the code which I wrote to convert it:
function convert(arr) {
var convertedArray = [];
$(arr).each(function () {
var found = false;
for (var i = 0; i < convertedArray.length; i++) {
if (convertedArray[i].name === this.name) {
found = true;
convertedArray[i].details.push({
"language": this.language,
"year": this.year
});
break;
}
}
if (!found) {
convertedArray.push({
"name": this.name,
"details": [{
"language": this.language,
"year": this.year
}]
});
}
});
return convertedArray;
}
I am sure there would be a better approach for this. But for me it worked.