【发布时间】:2019-04-01 07:33:55
【问题描述】:
我有一个 json 数组,格式如下:
[{
"published": true,
"tags": ["tag1", "tag2"],
"categories": ["cat1"],
"author": "some name",
"post-format": "standard",
"title": "Second Post,",
"url-slug": "second-post",
"first-published-on": "2019-03-28",
"last-updated-on": "2019-03-28",
"meta": {
"title": "Second Post",
"description": "Second post."
},
"excerpt": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt",
"path": "2019/03/28/SecondPost.md"
}, {
"published": true,
"tags": ["tag1", "tag2", "tag3"],
"categories": ["cat1", "cat2"],
"author": "some name",
"post-format": "standard",
"title": "Getting Started",
"url-slug": "getting-started",
"first-published-on": "2019-03-20",
"last-updated-on": "2019-03-20",
"meta": {
"title": "Getting Started",
"description": "Getting started post."
},
"excerpt": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt",
"path": "2019/03/20/GettingStarted.md"
}]
我想按标签对它们进行分组,格式如下:
[{
"tag1": [{...}, {...}],
"tag2": [{...}, {...}],
"tag3": [{...}]
}]
我曾尝试使用 lodash:
const groupedByTag = _.groupBy(blogMetadata, function(postmetadata) {
postmetadata.tags.map(tag => {
return tag
})
})
显然上面的代码不正确并且不起作用。我查看了相关的post,但没有取得太大进展。任何帮助表示赞赏。
【问题讨论】:
-
你可以试试 reduce 或 'json-groupby' nodejs 模块。
标签: javascript arrays json grouping lodash