Lodash 从重复的对象键创建集合

5

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

通过使用精简的lodash一行代码,我需要创建以下结构。

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

非常感谢你一如既往的帮助。关于解决方案如何工作的说明是一个巨大的加分项。


如果只有一条记录,titles 应该是数组吗? - Tushar
1
这个属性真的是'title:'吗? - Nina Scholz
@NinaScholz.. 很好地发现了。 - stackunderflow
3个回答

9
使用 _.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();

1
你缺少了.value()解析器来解析链式操作,否则你将得到一个LodashWrapper而不是所需的值,对于这种好的方法加1。 - amd

3
一个更好的lodash版本可以是(使用令人惊叹的“链式”方法):
_(a).groupBy('article').map( (x,k) => ({ article: k, titles:_.map(x, 'title')}) ).value();  

如果您想按文章分组(因此文章将成为关键字,有助于快速查找)
_(a).groupBy('article').mapValues(x => _.map(x, 'title')).value();

这不是相同的答案吗?你在解决方案中添加了一个箭头函数,但除此之外,你的答案只有第二部分是新的。 - 4castle
@4castle,实际上我没有检查过你的答案,但是你的原始答案有点不同(我认为你使用了_.chain),即使现在你的答案也不正确,因为你在最后缺少了.value()解析器。 - amd
它的功能正常,但我之前也误以为只有在使用.chain()时才需要.value()。这就是为什么我转而使用构造函数的原因。 - 4castle

2

一个纯Javascript的提案

它使用IIFE(立即调用函数表达式)来使用私有变量,并将返回值收集到数组中。

除此之外,它还使用哈希表来引用正确的数组项。

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" }],
    newOutput = function (data) {
        var r = [];
        data.forEach(function (a) {
            if (!this[a.article]) {
                this[a.article] = { article: a.article, titles: [] };
                r.push(this[a.article]);
            }
            this[a.article].titles.push(a.title);
        }, Object.create(null));
        return r;
    }(output);
        
console.log(newOutput);


谢谢,不过如果有一个lodash的例子会更好。只是为了简洁明了。 - stackunderflow

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接