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

139
Views
Typescript object with arrays to array

I need some help solving this :)

I want to transfer the object to an array. The expected result should be:

result = [
  {
    id: 'test-1',
    message: 'test#1.1'
  },
  {
    id: 'test-1',
    message: 'test#1.2'
  },
  {
    id: 'test-2',
    message: 'test#2.1'
  },
  {
    id: 'test-2',
    message: 'test#2.2'
  }
]

My apparent solution is with objects.keys() and map(). Unfortunately, this does not work as desired:

mockData = {
  'test-1': [
    {
      message: 'test#1.1'
    },
    {
      message: 'test#1.2'
    }
  ],
  'test-2': [
    {
      message: 'test#2.1'
    },
    {
      message: 'test#2.2'
    }
  ]
}

const result = Object.keys(this.mockData).map((id) => {
  return {
    id,
    ...this.mockData[id],
  }
})

console.log(result)

do I have to put another map() over this.mockData[id]? what am I doing wrong and what is best practice here (maybe reduce()?)?

I hope you can help me

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

0

To ungroup you can flatMap the Object.entries of the grouped object with a nested map() call over the grouped array elements.

const mockData = { 'test-1': [{ message: 'test#1.1' }, { message: 'test#1.2' }], 'test-2': [{ message: 'test#2.1' }, { message: 'test#2.2' }] };

const result = Object.entries(mockData).flatMap(([id, vs]) => vs.map(v => ({ id, ...v })));

console.log(result);

Or using a for...of loop if you'd rather

const mockData = { 'test-1': [{ message: 'test#1.1' }, { message: 'test#1.2' }], 'test-2': [{ message: 'test#2.1' }, { message: 'test#2.2' }] };

const result = [];
for (const [id, messages] of Object.entries(mockData)) {
  for (const message of messages) {
    result.push({ id, ...message });
  }
}

console.log(result);

about 4 years ago · Juan Pablo Isaza Report

0

This will return the desire solution,

const arr = [];
Object.keys(mockData).forEach((key) => {
    mockData[key].forEach((data) => {
        arr.push({
            id: key, 
            message: data.message
        })
    })
})
about 4 years ago · Juan Pablo Isaza Report

0

Object.keys(mockData)
    .map((id) =>
      mockData[id].map((l) => {
        return { ...l, id };
      })
    )
    .flat()
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!