Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lodash create collection from duplicate object keys

I have the following structure:

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

From the above using an elegant lodash one-liner, I need to create the following structure.

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

Help as always, is greatly appreciated.. A huge plus for an explanation for how a solution would work.

like image 830
stackunderflow Avatar asked Jul 18 '16 13:07

stackunderflow


People also ask

What is _ get?

The _. get() function is an inbuilt function in the Underscore. js library of JavaScript which is used to get the value at the path of object. If the resolved value is undefined, the defaultValue is returned in its place. Syntax: _.get(object, path, [defaultValue])

Does Lodash Uniq work on objects?

Lodash's 'uniq' family of methods can be implemented in plain JS without trouble. Lodash is a very useful utility library that lets us work with objects and arrays easily.

How do you remove duplicates in array of objects in Lodash?

We can remove duplicate elements from an array using the _. uniq() method of Lodash. This method keeps the first instance of an element and removes the remaining one. Therefore, the order of an element in the resultant array depends on its occurrence in the array.

Is Deep equal Lodash?

The Lodash _. isEqual() Method performs a deep comparison between two values to determine if they are equivalent. This method supports comparing arrays, array buffers, boolean, date objects, maps, numbers, objects, regex, sets, strings, symbols, and typed arrays.


1 Answers

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();
like image 145
4castle Avatar answered Oct 05 '22 23:10

4castle