当我从服务器中获取评论时,它以评论数组的形式出现。

[
    { content: "foo1", postId: 1 },
    { content: "foo2", postId: 1 },
    { content: "foo3", postId: 1 },
    { content: "foo4", postId: 2 },
    { content: "foo5", postId: 2 },
    { content: "foo6", postId: 3 }
]


我想将它们归类为一个对象:

{
    1: [
        { content: "foo1", postId: 1 },
        { content: "foo2", postId: 1 },
        { content: "foo3", postId: 1 }
    ],
    2: [
        { content: "foo4", postId: 2 },
        { content: "foo5", postId: 2 }
    ],
    3: [
        { content: "foo6", postId: 3 }
    ]
}


我敢肯定,这很容易,我尝试了使用groupBy或keyBy进行带lodash的许多组合,但我仍然找不到正确的答案。我正在使用lodash。

最佳答案

 var array = [
    { content: "foo1", postId: 1 },
    { content: "foo2", postId: 1 },
    { content: "foo3", postId: 1 },
    { content: "foo4", postId: 2 },
    { content: "foo5", postId: 2 },
    { content: "foo6", postId: 3 }
    ];

var formatedData = _.groupBy(array, 'postId');

10-06 09:58
查看更多