Reputation: 33
I have an array of objects like this:
[ { key: 'particles', value: 'GN' },
{ key: 'particles', value: 'TR' },
{ key: 'wave', value: 'AB' },
{ key: 'sense', value: 'TU' } ]
I need to get to something like:
[ { system.particles: ['GN', 'TR'] }, system.wave: {'AB'}, system.sense: {'TE'} } ]
I have tried to use lodash as I have seen from examples using the groupBy function. But I haven't been able to get what I want, which includes the key name changes.
This is a part of my code:
let exo = _.mapValues(_.groupBy(desc, 'key'),
clist => clist.map(tags => _.omit(desc, ['key'])))
But I only get this, which is not what I'm looking for
{ particles: [ { value: 'GN' }, { value: 'TR' } ],
wave: [ { value: 'AB' } ],
sense: [ { value: 'TU' } ] }
Upvotes: 1
Views: 138
Reputation: 2339
You can map like this
const data = [
{ key: 'particles', value: 'GN' },
{ key: 'particles', value: 'TR' },
{ key: 'wave', value: 'AB' },
{ key: 'wave', value: 'ABC' },
{ key: 'wave', value: 'ABD' },
{ key: 'sense', value: 'TU' }
];
const groupedData = _.map(_.groupBy(data, 'key'), (value, key) => {
const newKey = 'system.' + key;
return {[newKey]: _.map(value, 'value') };
});
console.log(groupedData);
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
Upvotes: 1