javascript - 通过标签重构嵌套的 JSON 数据 - Javascript
问题描述
我有一个带有帖子主题的 JSON 文件:
"topics": [
{
"id": "9551",
"tags": ["tag1", "tag2"],
"title": "title"
},
{
"id": "9552",
"tags": ["tag3"],
"title": "title2"
},
{
"id": "9553",
"tags": ["tag1"],
"title": "title3"
}
]
我想按标签对这些帖子进行排序,如下所示:
"tags" : {
"tag1": [
{ "id": "9951",
"title": "title"
},
{
"id": "9553",
"title": "title3"
}
],
"tag2": [
{
"id": "9551",
"title": "title"
}
]
}
我不确定以上内容是否有效,但本质上我想要原始数据的有效 JSON 输出,仅按标签排序。
感谢您的任何建议!
解决方案
您可以使用reduce
对标签进行分组。创建一个累加器,每个标签都为key
. 在 reduce 中,循环遍历每个tags
. 如果tag
已经添加了 a,则将{ id, title }
对象推送到数组中。否则,为该标签创建一个新数组,然后推送它。
const topics=[{"id":"9551","tags":["tag1","tag2"],"title":"title"},{"id":"9552","tags":["tag3"],"title":"title2"},{"id":"9553","tags":["tag1"],"title":"title3"}]
const group = topics.reduce((acc, { id, tags, title }) => {
tags.forEach(t => {
acc[t] = acc[t] || [];
acc[t].push({ id, title })
})
return acc;
}, {})
console.log({ tags: group })
推荐阅读
- php - 验证 Microsoft Graph 访问令牌
- angular - 如何在另一个组件中切换 mat-sidenav?
- javascript - 如何将数据从 HTML 发送到 .MDF 文件,从 .MDF 检索数据到 .EXE,并将结果从 .EXE 返回到 HTML?
- c++ - 为什么不执行“部分 RVO”?
- javascript - Material UI Snackbar 的背景颜色未被覆盖
- maven - 是否可以在 pom.xml 中使用条件
- php - 代码同时执行 if 和 else 语句我该如何解决?
- continuous-integration - 可以在 Nexus 中代理专有数据存储吗
- vba - 如何使用 VBScript 或 VBA 从 HTA 文件中获取值
- dart - 遍历嵌套地图时的 Null 感知运算符