Home > Back-end >  Typescript object with arrays to array
Typescript object with arrays to array

Time:06-03

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

CodePudding user response:

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);

CodePudding user response:

This will return the desire solution,

const arr = [];
Object.keys(mockData).forEach((key) => {
    mockData[key].forEach((data) => {
        arr.push({
            id: key, 
            message: data.message
        })
    })
})

CodePudding user response:

Object.keys(mockData)
    .map((id) =>
      mockData[id].map((l) => {
        return { ...l, id };
      })
    )
    .flat()
  • Related