interface GroupedItemsByCity {
cityRef: number
cityName: string,
items: Array<{
id: number,
itemName: string
}>
}
const groupedObject = returnObject.reduce<GroupedItemsByCity[]>((groupedArray, item) => {
// New slimmer item to push later
let refinedItem = {
id: item.id,
itemName: item.itemName
}
const matchedCity = groupedArray.find(city => city.cityRef === item.cityRef); // Check if the new structure already has a matching parent city for current item.
if (matchedCity) {
// If it does, push the item onto the existing city object.
matchedCity.items.push(refinedItem)
return groupedArray
}
// If it doesn't set up a new city and add the item to it
groupedArray.push({
cityRef: item.cityRef,
cityName: item.cityName,
items: [refinedItem]
})
return groupedArray
}, [])
console.log(groupedObject)
1条答案
按热度按时间2w2cym1i1#
工作TSPlayground。