Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

134
Views
Javascript reduce array of object into one object with keys

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?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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)

about 4 years ago · Juan Pablo Isaza Report

0

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)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!