Reputation: 39
I have this array of objects
[
{
"countryCode": "US",
"countryName": "United States",
"stateId": "1",
"stateName": "Alabama",
"cityId": "1",
"cityName": "Montgomery"
},
{
"countryCode": "US",
"countryName": "United States",
"stateId": "2",
"stateName": "Alabama",
"cityId": "2",
"cityName": "Birmingham"
},
{
"countryCode": "US",
"countryName": "United States",
"stateId": "2",
"stateName": "Alaska",
"cityId": "1",
"cityName": "Anchorage"
}
]
that I would like to convert to an object like the following
{
"countryCode": "US",
"countryName": "United States",
"states": [
{
"stateId": 1,
"stateName": "Alabama",
"cities": [
{
"cityId": 1,
"cityName": "Montgomery"
},
{
"cityId": 2,
"cityName": "Birmingham"
}
]
},
{
"stateId": 2,
"stateName": "Alaska",
"cities": [
{
"id": 1,
"name": "Anchorage"
}
]
}
]
}
I have tried lodash's groupBy
as var grouped = _.groupBy(data, 'countryCode')
but what I got is
{
HN: [
{
countryCode: 'US',
countryName: 'United States',
stateId: '1',
stateName: 'Alabama',
cityId: '1',
cityName: 'Montgomery'
},
{
countryCode: 'US',
countryName: 'United States',
stateId: '1',
stateName: 'Alabama',
cityId: '2',
cityName: 'Birmingham'
},
{
countryCode: 'US',
countryName: 'United States',
stateId: '2',
stateName: 'Alaska',
cityId: '1',
cityName: 'Anchorage'
}
]
}
I don't want the value of the property's name in which the data will be grouped by to be the key, I want the property's name being grouped by to be set as key and then create a custom property as an array to list all of the cities of a state, is there anyway to achieve this?
Thank you!
Upvotes: 0
Views: 80
Reputation: 1472
I think this is what you're looking for. This is also almost a duplicate of Javascript group objects by property
x = [{
"countryCode": "US",
"countryName": "United States",
"stateId": "1",
"stateName": "Alabama",
"cityId": "1",
"cityName": "Montgomery"
},
{
"countryCode": "US",
"countryName": "United States",
"stateId": "1",
"stateName": "Alabama",
"cityId": "2",
"cityName": "Birmingham"
},
{
"countryCode": "US",
"countryName": "United States",
"stateId": "2",
"stateName": "Alaska",
"cityId": "1",
"cityName": "Anchorage"
}
];
var stateArray = Object.values(x.reduce((result, {
countryCode,
countryName,
stateId,
stateName,
cityId,
cityName
}) => {
// Create new group
if (!result[0]) result[0] = {
countryCode,
countryName,
states: []
};
// Append to group
let state = -1;
for (let i = 0; i < result[0].states.length; i++) {
if (result[0].states[i].stateId == stateId)
state = i;
}
if (state == -1) {
result[0].states.push({
stateId,
stateName,
cities: [{
cityId,
cityName
}]
});
} else {
result[0].states[state].cities.push({
cityId,
cityName
});
}
return result;
}, {}));
console.log(stateArray)
Upvotes: 1