I have object with data:
const data = [
{
type: 'soccer',
price: '$10'
},
{
type: 'running',
price: '$5'
},
{
type: 'hockey',
price: '$15'
}
]
I want to convert it to object where key will be item.type:
const parsedData = {
soccer: {
type: 'soccer',
price: '$10'
},
running: {
type: 'running',
price: '$5'
},
hockey: {
type: 'hockey',
price: '$15'
}
}
I've defined enum with types: enum GameTypes { 'soccer', 'running', 'hockey' }
. And when I trying to use enum as key of object I'm getting error:
Element implicitly has an 'any' type because expression of type 'GameTypes' can't be used to index type 'GameProducts'.
Property '[GameTypes.lottery]' does not exist on type 'GameProducts'.ts(7053)
Full code:
enum GameTypes { 'soccer', 'running', 'hockey' }
type Game = {
type: GameTypes
price: string
}
type GameProducts = { [key in GameTypes]?: Game } | {}
const data: Array<Game> = [
{
type: 'soccer',
price: '$10'
},
{
type: 'running',
price: '$5'
},
{
type: 'hockey',
price: '$15'
}
]
// trying to format games in object
const formatGames: GameProducts = data.reduce((acc | {}, item) => {
if (!acc[item.type]) { // <-- error here
acc[item.type] = []
}
acc[item.type].push(item)
return acc
}, {})
What I'm doing wrong? Any other ways to do it?