我有一个带有帖子主题的 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 })
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句