Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transform an item into a key/value pair object in javascript?

I have a problem converting my data structure to a Key/Value Item.

I already tried some mapping and transformation, but my desired output is not shown on my console.

I have this code output of my function:

Console: {BLAU: Array(1), ROT: Array(2)}

and opened:

Console:

- BLAU: [{…}]
- ROT: (2) [{…}, {…}]

const vorher = [{
    BLAU: [{
      type: 'mytype1'
    }],
  },
  {
    ROT: [{
      type: 'mytype1'
    }],
    [{
      type: 'mytype2'
    }]
  }
];

My desired output should be something like this:

const nachher = [{
    farbe: 'BLAU',
    typen: [{
      type: 'mytype1'
    }]
  },
  {
    farbe: 'ROT',
    typen: [{
      type: 'mytype1'
    }],
    [{
      type: 'mytype2'
    }]
  },
];

EDIT:

I have something like this as output from a function [{…}, {…}, {…}], it looks like this:

[ { id: 100, system: {id: 101, label: "BLAU", createdAt: "2019-07-30"}, details: [{...},{...}], info: "Test" }, { id: 400, system: {id: 404, label: "ROT", createdAt: "2019-07-30"}, details: [{...},{...}], info: "Test" } ]

I want to group this one by system label with the desired output above. GroupBy only gives me an Object back.

like image 935
Maverick777 Avatar asked Jan 20 '26 02:01

Maverick777


1 Answers

You could take the first entry of the object, destructure it to the wanted key/value pair and retund a new object.

const
    data = [{ BLAU: [{ type: 'mytype1' }] }, { ROT: [{ type: 'mytype1' }, { type: 'mytype2' }] }],
    result = data.map(o => {
        var [farbe, typen] = Object.entries(o)[0];
        return { farbe, typen };
    });

console.log(result);
like image 163
Nina Scholz Avatar answered Jan 22 '26 14:01

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!