I attempted to organize JSON data based on city names using this fiddle code.
Now, I am trying to group the data by city name and city code. Any suggestions or hints regarding the logic would be greatly appreciated.
CurrentDataFormat = [{
"Id": 17,
"code": "123",
"cityName": "Los Angeles",
"cityCode": "LA",
"startDate": "1/20/2016",
"endDate": "1/20/2016"
},
{
"Id": 18,
"code": "456",
"cityName": "Chicago",
"cityCode": "CH",
"startDate": "1/22/2016",
"endDate": "1/25/2016"
},
{
"Id": 19,
"code": "789",
"cityName": "Los Angeles",
"cityCode": "LA",
"startDate": "1/13/2016",
"endDate": "1/21/2016"
}
]
GroupByJsonFormatData(CurrentDataFormat);
function GroupByJsonFormatData(CurrentDataFormat)
{
var refinedArray = {};
for (i = 0; i < CurrentDataFormat.length; i++) {
refinedArray[CurrentDataFormat[i].cityName] = refinedArray[CurrentDataFormat[i].cityName] ? refinedArray[CurrentDataFormat[i].cityName] : {};
refinedArray[CurrentDataFormat[i].cityName].name = CurrentDataFormat[i].cityName;
refinedArray[CurrentDataFormat[i].cityName].CityData = refinedArray[CurrentDataFormat[i].cityName].CityData ? refinedArray[CurrentDataFormat[i].cityName].CityData : [];
refinedArray[CurrentDataFormat[i].cityName].CityData.push({
"Id": CurrentDataFormat[i].Id,
"code": CurrentDataFormat[i].code,
"startDate": CurrentDataFormat[i].startDate,
"endDate": CurrentDataFormat[i].endDate
});
}
var ExpectedDataFormat = [];
for (singleCityName in refinedArray){
ExpectedDataFormat.push({'name' : refinedArray[singleCityName].name, 'CityData' : refinedArray[singleCityName].CityData});
};
console.log(ExpectedDataFormat);
document.getElementById("resultPane").innerHTML = JSON.stringify(ExpectedDataFormat, undefined, 2);;
}
I also tried to make this code more dynamic by passing column names as parameters. For instance, attempting something like GroupByJsonFormatData(CurrentDataFormat, GroupByColumn); and trying to concatenate this parameter with array like
refinedArray[CurrentDataFormat[i].+GroupByColumn]
but unfortunately, it did not work at the concatenation level.