Lodash create collection from duplicate object keys

Use _.groupBy and then _.map the resulting object to an array of objects.

var newOutput = _(output)
    .groupBy('article')
    .map(function(v, k){ return { article: k, titles: _.map(v, 'title') } })
    .value();

var output = [{"article":"BlahBlah","title":"Another blah"},{"article":"BlahBlah","title":"Return of the blah"},{"article":"BlahBlah2","title":"The blah strikes back"},{"article":"BlahBlah2","title":"The blahfather"}];

let newOutput = _(output)
    .groupBy('article')
    .map(function(v, k){ return { article: k, titles: _.map(v, 'title') } })
    .value();

console.log(newOutput);
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script>

With ES6 arrow-functions,

var newOutput = _(output)
    .groupBy('article')
    .map((v, k) => ({ article: k, titles: _.map(v, 'title') }))
    .value();

Leave a Comment