gpt4 book ai didi

javascript - 将值插入对象

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

我有以下内容

const post = [
{ postTitle: 'Title1', key: 'key1' },
{ postTitle: 'Title2', key: 'key2' }
];

const comment = [
{ key: 'key1', c: 'comment1' },
{ key: 'key1', c: 'comment2' },
{ key: 'key2', c: 'commentA' },
{ key: 'key2', c: 'commentB' },
{ key: 'key2', c: 'commentC' }
];

我想最终得到以下结果:

const newPost = [
{
postTitle: 'Title1',
key: 'key1',
comment: ['comment1', 'comment2']
},
{
postTitle: 'Title2',
key: 'key2',
comment: ['commentA', 'commentB', 'commentC']
}
];

下面的代码似乎几乎完成了这项工作,但它覆盖了我的评论。我只得到每个 postTitle 的最后一条评论。我怎样才能修复代码或改进代码以获得与上面的结果完全相同的结果?

这是有问题的代码:

for (var i = 0; i < post.length; ++i) {
for (var j = 0; j < comment.length; j++) {
if (post[i].key === comment[j].key) {
post[i].comment = [];
post[i].comment.push([comment[j].c]);
} else {
console.log('no comment to add');
}
}
}

另外,如果有更优雅的重构代码,请在这里分享。谢谢。

最佳答案

稍微不同的方法会扫描一次评论以将它们组合起来,然后使用生成的对象作为映射帖子的查找:

const combine = (posts, comments) => {
const keyedComments = comments .reduce (
(a, {key, c}) => (a [key] = (a [key] || [] ) .concat(c), a),
{}
)
return posts .map ( ({key, ...rest}) => ({
...rest,
comment: keyedComments [key] || []
}))
}

const post = [{postTitle : 'Title1', key: 'key1'}, {postTitle : 'Title2', key: 'key2'}]
const comment = [{key : 'key1', c: "comment1"}, {key : 'key1', c: "comment2"}, {key : 'key2', c: "commentA"}, {key : 'key2', c: "commentB"}, {key : 'key2', c: "commentC"}]

console .log (
combine (post, comment)
)

关于javascript - 将值插入对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56213200/

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