使用lodash .groupBy。如何为分组输出添加自己的密钥? [英] using lodash .groupBy. how to add your own keys for grouped output?

查看:198
本文介绍了使用lodash .groupBy。如何为分组输出添加自己的密钥?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从API返回此示例数据。

I have this sample data returned from an API.

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

I'm using Lodash's _.groupBy to convert the data into an object I can use better. The raw data returned is this:

[
    {
        "name": "jim",
        "color": "blue",
        "age": "22"
    },
    {
        "name": "Sam",
        "color": "blue",
        "age": "33"
    },
    {
        "name": "eddie",
        "color": "green",
        "age": "77"
    }
]

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

I want the _.groupBy function to return an object that looks like this:

[
    {
        color: "blue",
        users: [
            {
                "name": "jim",
                "color": "blue",
                "age": "22"
            },
            {
                "name": "Sam",
                "color": "blue",
                "age": "33"
            }
        ]
    },
    {
        color: "green",
        users: [
            {
                "name": "eddie",
                "color": "green",
                "age": "77"
            }
        ]
    }
]

目前我正在使用

_.groupBy(a, function(b) { return b.color})

返回此信息。

{blue: [{..}], green: [{...}]}

分组是正确的,但我真的想添加我想要的键(颜色用户)。这可能是使用 _。groupBy ?或其他一些 LoDash 实用程序?

the groupings are correct, but I'd really like to add the keys I want (color, users). is this possible using _.groupBy? or some other LoDash utility?

推荐答案

你可以这样做

var result = _.chain(data)
    .groupBy("color")
    .pairs()
    .map(function(currentItem) {
        return _.object(_.zip(["color", "users"], currentItem));
    })
    .value();
console.log(result);

在线演示

注意: Lodash 4.0起, .pairs 功能已经已重命名为 _。toPairs()

Note: Lodash 4.0 onwards, the .pairs function has been renamed to _.toPairs()

这篇关于使用lodash .groupBy。如何为分组输出添加自己的密钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆