Ckappo
Ckappo

Reputation: 597

lodash merge one object

I want to use lodash to manipulate and formate a JSON object. After several (parallel) functions, I get a Object like this (the Object is the result of all parallel tasks):

 obj: [ { id: '1',
    count: 100 },
  { id: '2',
    count: 50 },
  { id: '3',
    count: 10 },
  { id: '1',
    type: A},
  { id: '2',
    type: B },
  { id: '3',
    type: C },
  { id: '1',
    other: no },
  { id: '2',
    other: no},
  { id: '3',
    other: yes},
  { input: 'key',
    output: 'screen',
    match: 'no',
    id: '1' },
  { input: 'key',
    output: 'screen',
    match: 'yes',
    id: '2' },
  { buy: '100',
    id: '1' },
  { buy: '200',
    id: '3' } ]

My Output should combine the object, group By the id. Like that:

 [ { id: '1',
    count: '',
    other: '',
    input: '',
    output: '',
    match: '',
    buy: ''},
 { id: '2',
    count: '',
    other: '',
    input: '',
    output: '',
    match: '',
    buy: ''},
  { id: '3',
    count: '',
    other: '',
    input: '',
    output: '',
    match: '',
    buy: ''} ]

My attempt to achiev this, is to group by id and map it. So I create a new object and chain lodash functions.

var result=_(obj)
           .groupBy('id')
           .map((objs, key) => ({
               'id': key,
               'count': (_.map(objs, 'count')),
               'other': (_.map(objs, 'other')),
               'input': (_.map(objs, 'input')),
               'output': (_.map(objs, 'output')),
               'match': (_.map(objs, 'match')),
               'buy': (_.map(objs, 'buy')),
  }))
  .value();

The id field is correct but all other fields are bad.

for example the count field (id= 1):

[ 100, undefined, undefined ]

count field (id= 2):

[ undefined, 50, undefined ]

What should I do?

Upvotes: 0

Views: 97

Answers (1)

Ori Drori
Ori Drori

Reputation: 191976

Since each group is an array of objects, you can use _.merge() with the spread syntax to combine the group to a single object:

const data = [{"id":"1","count":100},{"id":"2","count":50},{"id":"3","count":10},{"id":"1","type":"A"},{"id":"2","type":"B"},{"id":"3","type":"C"},{"id":"1","other":"no"},{"id":"2","other":"no"},{"id":"3","other":"yes"},{"input":"key","output":"screen","match":"no","id":"1"},{"input":"key","output":"screen","match":"yes","id":"2"},{"buy":"100","id":"1"},{"buy":"200","id":"3"}];

var result = _(data)
  .groupBy('id')
  .map((objs) => _.merge({
    count: '',
    other: '',
    input: '',
    output: '',
    match: '',
  }, ...objs))
  .value();
  
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

Upvotes: 2

Related Questions