gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:07:13 25 4
gpt4 key购买 nike

我有以下结构:

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();

关于javascript - Lodash 从重复的对象键创建集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38438645/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com