Lodash从重复的对象键创建集合 [英] Lodash create collection from duplicate object keys

查看:346
本文介绍了Lodash从重复的对象键创建集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下结构:

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 one-liner,我需要创建以下结构。

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.

推荐答案

使用 _。groupBy 然后 _。map 生成的对象为对象数组。

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>

使用ES6箭头函数,

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

这篇关于Lodash从重复的对象键创建集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆