使用lodash合并数组的不同行

时间:2016-10-07 00:10:48

标签: lodash

我有一个JSON数组,其中包含以下条目:

[{"customer":"xyz","date":"10.10.2014","attr1":"ABC","attr2":"001"},{"customer":"xyz","date":"10.10.2014","attr3":"XYZ","attr4":"123"},{"customer":"xyz","date":"11.10.2014","attr1":"DEF","attr2":"002"},{"customer":"xyz","date":"11.10.2014","attr3":"DDD","attr4":"222"}]

有没有办法,使用lodash,我可以合并数组,使其变为:

[{"customer":"xyz","date":"10.10.2014","attr1":"ABC","attr2":"001","attr3":"XYZ","attr4":"123"},{"customer":"xyz","date":"11.10.2014","attr1":"DEF","attr2":"002","attr3":"DDD","attr4":"222"}]

基本上使用" date"用于将具有不同JSON属性的多个行合并到单个JSON对象条目中的属性?

2 个答案:

答案 0 :(得分:1)

使用_.groupBy()按日期对对象进行分组。然后_.merge()每个小组:



var customers = [{"customer":"xyz","date":"10.10.2014","attr1":"ABC","attr2":"001"},{"customer":"xyz","date":"10.10.2014","attr3":"XYZ","attr4":"123"},{"customer":"xyz","date":"11.10.2014","attr1":"DEF","attr2":"002"},{"customer":"xyz","date":"11.10.2014","attr3":"DDD","attr4":"222"}];

var result = _(customers)
  .groupBy('date') // group the objects by date
  .map(function(item) { // map each group
    return _.merge.apply(_, item); // merge all objects in the group
  })
  .value();

console.log(result);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

这是使用lodash 3.10.1的解决方案。我假设你想合并每一对,并且一对中的第二个元素将覆盖第一个元素的现有属性(如果有的话)。

var source  = [{"customer":"xyz","date":"10.10.2014","attr1":"ABC","attr2":"001"},{"customer":"xyz","date":"10.10.2014","attr3":"XYZ","attr4":"123"},{"customer":"xyz","date":"11.10.2014","attr1":"DEF","attr2":"002"},{"customer":"xyz","date":"11.10.2014","attr3":"DDD","attr4":"222"}];

var chunked = _.chunk(source, 2);

var result = _.map(chunked, _.spread(_.merge));

console.log(result);

这是一个working jsbin