我有一个数组categories,它的值id我试图与我的数组匹配articles
如果articles有一个匹配的 id 与我喜欢的其中之一,categories会将它们合并到一个数组中。我可以将这些对象添加到数组中,但它们根据 id 不匹配。
以下是类别的示例:
const categories = [{results:
{
"id": 28,
"name": "Articles"
}, {
"id": 76,
"name": "Projects"
}
}]
Run Code Online (Sandbox Code Playgroud)
以下是文章示例:
const articles = [
{
"title": "first article",
"content": "lorem ipsum",
"categoryId": 28
},
{
"title": "second article",
"content": "lorem ipsum",
"categoryId": 28
},
{
"title": "thirdarticle",
"content": "lorem ipsum",
"categoryId": 76
},
]
Run Code Online (Sandbox Code Playgroud)
我正在尝试将两个数组合并为一个。如果可能的话,我希望该articles数组成为该匹配索引中的数组。例如:
const combined = [
{
"id": 28,
"name": "Articles",
"articles:: [
{ "title": "first article", "content": "lorem ipsum", "categoryId": 28 },
{ "title": "second article", "content": "lorem ipsum", "categoryId": 28 },
],
},
];
Run Code Online (Sandbox Code Playgroud)
我尝试通过类别映射并使用Object.assign. 输出结果似乎组合了数组,但我相信它们都是组合的并且与 id 不匹配。
我怎样才能实现这一目标?
const categories = [{results:
{
"id": 28,
"name": "Articles"
}, {
"id": 76,
"name": "Projects"
}
}]
Run Code Online (Sandbox Code Playgroud)
这是使用代码到达那里的一种方法,但过滤匹配的文章并使用spread运算符
let combined = categories.results.map(item => ({ ...item,
articles: articles.filter(f => f.categoryId == item.id)
}));
Run Code Online (Sandbox Code Playgroud)
let combined = categories.results.map(item => ({ ...item,
articles: articles.filter(f => f.categoryId == item.id)
}));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2578 次 |
| 最近记录: |