lodash合并一个对象

时间:2018-05-02 12:02:34

标签: javascript lodash

我想使用lodash来操作和合成JSON对象。 在几个(并行)函数之后,我得到一个像这样的Object(Object是所有并行任务的结果):

 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组成。像那样:

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

我实现这一目标的尝试是按ID分组并映射它。所以我创建了一个新的对象和链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字段正确但所有其他字段都不正确。

例如count字段(id = 1):

  

[100,undefined,undefined]

计数字段(id = 2):

  

[undefined,50,undefined]

我该怎么办?

1 个答案:

答案 0 :(得分:2)

由于每个组都是一个对象数组,因此您可以将_.merge()spread syntax结合使用,将该组合并为一个对象:



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>
&#13;
&#13;
&#13;