As a front-end developer, I am given the following result from an API, an array of objects that looks like:
[{
Color: "#065b79",
GroupName: "VXYZ",
QuoteCount: 4,
SortOrder: 0,
TabCategoryID: "CHSI1",
TabCategoryName: "Workers' Compensation",
TabCategoryOrder: 0,
TabID: 1,
TabName: "new"
}]
I need to display the data in a more hierarchical/nested format:
[{
GroupName: 'VXYZ',
TabCategories: [
{
TabCategoryID: 'CHSI1',
TabCategoryName: "Workers' Compensation",
TabCategoryOrder: 0,
Tabs: [
{
Color: '#065b79',
SortOrder: 0,
TabID: 1,
TabName: 'new',
QuoteCount: 4
}
]
}
]
}]
Any data in an array can have any number of array items. In the models above, I just use a single instance of each array item.
This is the code I used to format the data
I'm using Typescript and lodash. The API is experimental, and our policy is to just use the any
type for any data coming from experimental APIs. This explains the (Quotes: any)
— it is the data from the API.
public FormatQuoteSummaries(Quotes: any): any {
return _(Quotes)
.map(Quote => Quote.GroupName)
.uniq()
.map(UniqueGroupName => {
const GroupName = UniqueGroupName
const AllTabCategories = _.filter(Quotes, (Quote: any) => {
return Quote.GroupName === UniqueGroupName
})
const TabCategories = _(AllTabCategories).map(TabCategory => {
return {
TabCategoryID: TabCategory.TabCategoryID,
TabCategoryName: TabCategory.TabCategoryName,
Tabs: _.filter(Quotes, (Quote: any) => {
return Quote.TabCategoryName === TabCategory.TabCategoryName &&
Quote.GroupName === TabCategory.GroupName
})
}
})
.uniqBy('TabCategoryID')
.value();
return {
GroupName,
TabCategories
}
})
.value();
}