0

I have a JSON array which has the following entries:

[{"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"}]

Is there a way, using lodash, I can merge the array so that this becomes:

[{"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"}]

Basically use the "date" attribute to merge multiple rows with different JSON attributes into a single JSON object entry ?

3
  • What should happen if the date values are the same but the customer values are different (is that not possible with your data)? Commented Oct 7, 2016 at 0:46
  • The customer would be the same always. Commented Oct 7, 2016 at 0:47
  • What version of lodash are you using? Commented Oct 7, 2016 at 9:44

2 Answers 2

1

Use _.groupBy() to group the objects by date. Then _.merge() each group:

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>

Sign up to request clarification or add additional context in comments.

Comments

0

Here is a solution using lodash 3.10.1. I assumed you want to merge each pair and that the second element of a pair will override existing properties from the first one (if there are such).

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

And here is a working jsbin.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.