How do I turn one object into multiple objects depending on how many keys there are?

I have a simple question.

I want to turn this array of one object...

[
    {
        id: 1,
        caseId: "Default Case Set",
        casenbr: "CASEWORK",
        submitterCasenbr: 34,
        othref: 0,
        sta: 0,
        type: 0,
        create: 0,
        startd: 0
    }
]

into an array of multiple objects like this...

[
    {
        id: 1
    },
    {
        caseId: "Default Case Set"
    },
    {
        casenbr: "CASEWORK"
    },
    {
        submitterCasenbr: 34
    },
    {
        othref: 0
    },
    {
        sta: 0
    },
    {
        type: 0
    },
    {
        create: 0
    },
    {
        startd: 0
    }
]

What would be the best approach to do this? Basically, I want to take all the key/value pairs in the object and turn them each into objects.

So, if I have an array of one object with 100 key/value pairs, I'd want to create one array of 100 objects that have only one key/value pair.

The reason I'm doing this is to create an array that I can use for an ngFor directive in my Angular 13 app.

I don't know if there is a way for ngFor in Angular to repeat over the key/value pairs of one object in one array, so that's what I'm creating one array of multiple objects.


Solution 1:

I don't think this question should of been closed as the answer is more in line with how to use ngFor.

If you want to loop over say your array but then loop over all your keys as columns you could have something like this:

<table>
  <thead>
    <tr>
      <th *ngFor="let column of data[0] | keyvalue">
        {{ column.key }}
      </th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let row of data">
      <td *ngFor="let column of row | keyvalue">
         {{ column.value }}
      </td>
    </tr>
  </tbody>
</table>

This would give you a table (along with headers) mimicking your data. See this stackblitz: https://stackblitz.com/edit/angular-daubr3?file=src%2Fapp%2Fapp.component.html