我尝试使用this fiddle代码按城市名称格式化json组。

我正在尝试将相同的代码与城市名称和城市代码分组。任何逻辑提示都会有所帮助。

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);;
}


我还尝试通过在参数中传递列名来使此代码通用。
例如,我尝试像GroupByJsonFormatData(CurrentDataFormat,GroupByColumn);并尝试将此参数列附加到数组

excellentArray [CurrentDataFormat [i]。+ GroupByColumn]

但它在串联级别上不起作用。

最佳答案

您可以使用以下方法简化代码:

refinedArray[CurrentDataFormat[i].cityName] = refinedArray[CurrentDataFormat[i].cityName] || {};


代替

refinedArray[CurrentDataFormat[i].cityName] = refinedArray[CurrentDataFormat[i].cityName] ? refinedArray[CurrentDataFormat[i].cityName] : {};


与数组相同:

refinedArray[CurrentDataFormat[i].cityName].CityData = refinedArray[CurrentDataFormat[i].cityName].CityData || [];


对于通用实现,您可以使用

refinedArray[CurrentDataFormat[i]][GroupByColumn]

09-25 19:38