1

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?

4
  • 1
    What's your expected outcome when two items have the same intervalId ? Commented Feb 2, 2022 at 11:54
  • Why Object.keys() with an array? Why for...of...? Why .map() in the for...of... loop? Why .map() for a single element? And why is there no TypeError in your question that will be thrown by calling .map() on an object (entryPenaltyGroups[key].map(...))? -> How do I ask a good question? Commented Feb 2, 2022 at 11:55
  • @malarres they don't have same intervalId 8 and 16 are Commented Feb 2, 2022 at 11:56
  • ok @VladimirŠtus then check my answer with reduce Commented Feb 2, 2022 at 11:59

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

0
entryPenaltyGroups.reduce((acc, el)=>((acc[el.intervalId] = el.penaltyTime),acc),{})

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.