相关疑难解决方法(0)

使用lodash .groupBy.如何为分组输出添加自己的密钥?

我有一个从API返回的示例数据.

我正在使用Lodash _.groupBy将数据转换为我可以更好地使用的对象.返回的原始数据是:

[
    {
        "name": "jim",
        "color": "blue",
        "age": "22"
    },
    {
        "name": "Sam",
        "color": "blue",
        "age": "33"
    },
    {
        "name": "eddie",
        "color": "green",
        "age": "77"
    }
]
Run Code Online (Sandbox Code Playgroud)

我希望_.groupBy函数返回一个如下所示的对象:

[
    {
        color: "blue",
        users: [
            {
                "name": "jim",
                "color": "blue",
                "age": "22"
            },
            {
                "name": "Sam",
                "color": "blue",
                "age": "33"
            }
        ]
    },
    {
        color: "green",
        users: [
            {
                "name": "eddie",
                "color": "green",
                "age": "77"
            }
        ]
    }
]
Run Code Online (Sandbox Code Playgroud)

目前我正在使用

_.groupBy(a, function(b) { return b.color})
Run Code Online (Sandbox Code Playgroud)

这是归还这个. …

javascript sorting grouping underscore.js lodash

85
推荐指数
7
解决办法
13万
查看次数

标签 统计

grouping ×1

javascript ×1

lodash ×1

sorting ×1

underscore.js ×1