Лодаш слить один объект - PullRequest
0 голосов
/ 02 мая 2018

Я хочу использовать lodash для манипулирования и формирования объекта JSON. После нескольких (параллельных) функций я получаю такой объект (этот объект является результатом всех параллельных задач):

 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' } ]

Мой вывод должен объединять объект, группу по идентификатору. Вот так:

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

Моя попытка достичь этого - сгруппировать по идентификатору и отобразить это. Поэтому я создаю новый объект и цепочку функций lodash.

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

Поле id верное, но все остальные поля неверны.

например поле подсчета (id = 1):

[100, не определено, не определено]

поле подсчета (id = 2):

[не определено, 50, не определено]

Что мне делать?

1 Ответ

0 голосов
/ 02 мая 2018

Поскольку каждая группа является массивом объектов, вы можете использовать _.merge() с синтаксисом для объединения группы в один объект:

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>
...