Hello i am trying to repack array of objects and convert it into one object with specific keys. So here is array:
const entryPenaltyGroups = [
{ entryId: 16, intervalId: 8, penaltyTime: 16000 },
{ entryId: 16, intervalId: 10, penaltyTime: 6000 }
]
Expected result should be:
{
'8': {
penaltyTime: 16000
},
'10': {
penaltyTime: 6000
}
}
I have tried something with map(), but not getting expected results.
for (const entry of entryPenaltyGroups) {
entry.map(x => [{
[x.intervalId]: {
penaltyTime: x.intervalId
},
}])
}
Should i use reduce() instead maybe?
You can map the array into [key, value] pairs, and then use Object.fromEntries to convert the mapped array into a single object:
Object.fromEntries(entryPenaltyGroups.map(
({intervalId, penaltyTime}) => [intervalId, {penaltyTime}]
))
Alternatively:
Object.fromEntries(entryPenaltyGroups.map(
entry => [entry.intervalId, {penaltyTime: entry.penaltyTime}]
))
If there are any duplicate keys, the last occurrence will be used in the resulting object.
A solution with reduce. This will override the item if they have the same intervalId , but OP commented that this is not a problem for them
const entryPenaltyGroups = [
{ entryId: 16, intervalId: 8, penaltyTime: 16000 },
{ entryId: 16, intervalId: 10, penaltyTime: 6000 }
]
const result = entryPenaltyGroups.reduce( (acc,cur) => {
acc[cur.intervalId] = {penaltyTime: cur.penaltyTime};
return acc;
}
,{})
console.log(result)
const entryPenaltyGroups = [
{ entryId: 16, intervalId: 8, penaltyTime: 16000 },
{ entryId: 16, intervalId: 10, penaltyTime: 6000 }
]
const formatted = {}
for(entry of entryPenaltyGroups){
formatted[entry.intervalId] = {penaltyTime: entry.penaltyTime}
}
console.log(formatted)