[英]Flattening an array of objects into another array of objects using javascript
我已经在多种上下文和语言中遇到了这个问题,并且我始终能够解决该问题,但是我想最终想出一个合适的模式来处理此问题。 它来自联接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]} })
}
您也可以使用filter()
:
function combine(src) {
var dict = {};
return src.filter(function(item) {
if (!dict[item.itemId]) {
item.comments = [ item.comments ];
dict[item.itemId] = item;
return true;
} else {
dict[item.itemId].comments.push(item.comments);
return false;
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.