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.
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])
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.
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With