gpt4 book ai didi

Javascript - 将对象添加到具有匹配 id 的数组

转载 作者:行者123 更新时间:2023-12-05 01:25:55 25 4
gpt4 key购买 nike

我有一个数组categories,它的值为id,我试图将其与我的数组articles

匹配

如果 articles 有一个与 categories 之一匹配的 id,我想将它们组合成一个数组。我能够将这些对象添加到数组中,但它们不基于 id 进行匹配。

这是一个类别的例子:

const categories = [{results: 
{
"id": 28,
"name": "Articles"
}, {
"id": 76,
"name": "Projects"
}
}]

这里是一个文章的例子:

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
},
]

我正在尝试将两个数组合二为一。如果可能的话,我希望 articles 数组是该匹配索引中的一个数组。例如:

 const combined = [
{
"id": 28,
"name": "Articles",
"articles:: [
{ "title": "first article", "content": "lorem ipsum", "categoryId": 28 },
{ "title": "second article", "content": "lorem ipsum", "categoryId": 28 },
],
},
];

我尝试通过类别映射和使用 Object.assign 来实现这一点。输出结果似乎组合了数组,但我相信它们都是组合的并且与 id 不匹配。

我怎样才能做到这一点?

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
},
]


const categories = {results: [{ "id": 28, "name": "Articles"}, {"id": 76, "name": "Projects"}]}

let combined = categories.results.map((item, i ) => Object.assign(item, articles));

console.log(combined)

最佳答案

这是使用您的代码实现该目标的一种方法,但会过滤匹配的文章并使用 spread 运算符

let combined = categories.results.map(item => ({ ...item,
articles: articles.filter(f => f.categoryId == item.id)
}));

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
},
]


const categories = {
results: [{
"id": 28,
"name": "Articles"
}, {
"id": 76,
"name": "Projects"
}]
}

let combined = categories.results.map(item => ({ ...item,
articles: articles.filter(f => f.categoryId == item.id)
}));

console.log(combined)

关于Javascript - 将对象添加到具有匹配 id 的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70601253/

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