对象数组Js的组元素

时间:2018-11-08 19:45:59

标签: javascript arrays angular typescript

数小时以来,我一直在尝试将数组中具有相同值的元素分组,但我却一事无成

数组:

list = [
    {id: "0", created_at: "foo1", value: "35"},
    {id: "1", created_at: "foo1", value: "26"},
    {id: "2", created_at: "foo", value: "13"},
    {id: "3", created_at: "foo1", value: "11"},
    {id: "4", created_at: "foo", value: "11"},
    {id: "5", created_at: "foo1", value: "16"},
    {id: "6", created_at: "foo", value: "26"},
    {id: "7", created_at: "foo1", value: "13"},
    {id: "8", created_at: "foo1", value: "16"}
];

我想要得到的结果是:

var result = [
    [
        {id: "0", created_at: "foo1", value: "35"}
    ],
    [
        {id: "1", created_at: "foo1", value: "26"},
        {id: "6", created_at: "foo", value: "26"}
    ],
    [
        {id: "2", created_at: "foo", value: "13"},
        {id: "7", created_at: "foo1", value: "13"}
    ],
    [
        {id: "3", created_at: "foo1", value: "11"},
        {id: "4", created_at: "foo", value: "11"}
    ],
    [
        {id: "5", created_at: "foo1", value: "16"},
        {id: "8", created_at: "foo1", value: "16"}
    ]         
];

有什么想法怎么做到的?预先感谢。

注意:我正在使用角度5。

1 个答案:

答案 0 :(得分:1)

如果您正在考虑使用Lodash,则可以使用 _.groupBy

var list = [
    {id: "0", created_at: "foo1", value: "35"},
    {id: "1", created_at: "foo1", value: "26"},
    {id: "2", created_at: "foo", value: "13"},
    {id: "3", created_at: "foo1", value: "11"},
    {id: "4", created_at: "foo", value: "11"},
    {id: "5", created_at: "foo1", value: "16"},
    {id: "6", created_at: "foo", value: "26"},
    {id: "7", created_at: "foo1", value: "13"},
    {id: "8", created_at: "foo1", value: "16"}
];

var response = _.groupBy(list, 'value');

console.log(response);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>