gpt4 book ai didi

javascript - 使用javascript将一个对象数组展平为另一个对象数组

转载 作者:数据小太阳 更新时间:2023-10-29 05:33:45 24 4
gpt4 key购买 nike

我在多种环境和语言中遇到过这个问题,我总是能够解决它,但我想最终找到一个合适的模式来处理这个问题。它来自连接 SQL 表。通常我会打两个电话,一个用于项目,一个用于评论,但我知道有一种方法可以在一个电话中完成所有操作,然后将结果拉平。

我想做的是采用如下所示的数组:

[
{
itemId: 1,
comments: {
commentId: 1
}
},
{
itemId: 1,
comments: {
commentId: 2
}
},
{
itemId: 2,
comments: {
commentId: 3
}
}
]

然后把它变成这样:

[
{
itemId: 1,
comments: [
{
commentId: 1
},
{
commentId: 2
}
]
},
{
itemId: 2,
comments: [
{
commentId: 3
}
]
}
]

最佳答案

以下应该适合您:

function combine(arr) {
var newObj = {};

// combine the comments
for (var i=0; i < arr.length; i++) {
if (newObj[arr[i].itemId]) {
newObj[arr[i].itemId].push(arr[i].comments);
} else {
newObj[arr[i].itemId] = [arr[i].comments];
}
}

// make the list
var keys = Object.keys(newObj);
return keys.map(function(key){return {itemId: key, comments: newObj[key]} })
}

关于javascript - 使用javascript将一个对象数组展平为另一个对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16953587/

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