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

6 javascript arrays design-patterns object

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

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

[
  {
    itemId: 1,
    comments: {
      commentId: 1
    }
  },
  {
    itemId: 1,
    comments: {
      commentId: 2
    }
  },
  {
    itemId: 2,
    comments: {
      commentId: 3
    }
  }
]
Run Code Online (Sandbox Code Playgroud)

把它变成这个:

[
  {
    itemId: 1,
    comments: [
      {
        commentId: 1
      },
      {
        commentId: 2
      }
    ]
  },
  {
    itemId: 2,
    comments: [
      {
        commentId: 3
      }
    ]
  }
]
Run Code Online (Sandbox Code Playgroud)

And*_*rew 1

以下内容应该适合您:

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]} })
}
Run Code Online (Sandbox Code Playgroud)