我有以下结构:
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"
}]
从上面使用优雅的lodash单线程,我需要创建以下结构.
var newOutput = [{
"article": "BlahBlah",
"titles": ["Another blah", "Return of the blah"]
}, {
"article": "BlahBlah2",
"titles": ["The blah strikes back", "The blahfather"]
}]
非常感谢帮助..对解决方案如何工作的解释是一个巨大的优势.
解决方法:
将结果对象使用_.groupBy
然后_.map
到一个对象数组.
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>
使用ES6箭头功能,
var newOutput = _(output)
.groupBy('article')
.map((v, k) => ({ article: k, titles: _.map(v, 'title') }))
.value();