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

时间:2016-07-18 13:57:58

标签: javascript arrays object 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单线程,我需要创建以下结构。

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

一如既往地提供帮助,非常感谢..对于解决方案如何运作的解释是一个巨大的优势。

3 个答案:

答案 0 :(得分:4)

使用_.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>
&#13;
&#13;
&#13;

使用ES6箭头功能,

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

答案 1 :(得分: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);

答案 2 :(得分:2)

更好的lodash版本可能是(使用了很棒的chaining方法)

_(a).groupBy('article').map( (x,k) => ({ article: k, titles:_.map(x, 'title')}) ).value();  

如果您想按文章分组(因此文章将是关键,对快速查找很有用)

_(a).groupBy('article').mapValues(x => _.map(x, 'title')).value();