使用Lodash统计两个标准

时间:2014-09-05 01:02:13

标签: javascript json nested underscore.js lodash

我无法弄清楚如何根据位置和唯一的序列号计算总设备数。

{
"dates": [
    {
        "date": "Sep 1, 2014",
        "devices": [
            {
                "model": "Canon",
                "location": "Chicago",
                "serialNum": "abc123"
            },
            {
                "model": "Canon",
                "location": "Chicago",
                "serialNum": "xyz456"
            },
            {
                "model": "HP",
                "location": "New York",
                "serialNum": "123456"
            },
            {
                "model": "Brother",
                "location": "Chicago",
                "serialNum": "DEF777"
            }
        ]
    },
    {
        "date": "Sep 2, 2014",
        "devices": [
            {
                "model": "Canon",
                "location": "Chicago",
                "serialNum": "abc123"
            },
            {
                "model": "Canon",
                "location": "Chicago",
                "serialNum": "xyz456"
            }
        ]
    },
    {
        "date": "Sep 3, 2014",
        "devices": [
            {
                "model": "Canon",
                "location": "Chicago",
                "serialNum": "xyz456"
            },
            {
                "model": "Canon",
                "location": "Chicago",
                "serialNum": "stu789"
            },
            {
                "model": "Epson",
                "location": "NewYork",
                "serialNum": "123456"
            },
            {
                "model": "Epson",
                "location": "NewYork",
                "serialNum": "555555"
            },
            {
                "model": "HP",
                "location": "NewYork",
                "serialNum": "987654"
            }
        ]
    }
]

}

我想捕获每个位置的唯一设备总数

Chicago - 4
New York - 3

1 个答案:

答案 0 :(得分:2)

这是一个带有lodash链语法的单个表达式。简短版本是您将所有设备放入一个庞大的列表,然后按位置对它们进行分组,然后为每个位置消除重复的ID,然后计算设备。

_(dates) //Begin chain
    .pluck("devices") //get the device list for each date
    .flatten() //combine all device lists into a master list
    .groupBy("location") //group into an object of {"location": [devices]} pairs
    .mapValues(function (devicesForLocation) { //replaces [devices] with a count of number of unique serial numbers
        return _(devicesForLocation) //Begin chain
            .pluck("serialNum") //get the serial number for each device
            .uniq() //remove the duplicate serial numbers
        .value() //End chain
        .length; // get the count of unique serial numbers
    }) // result is an object of {"location": countOfUniqueDevices} pairs
.value() //End chain

最终结果是一个形式的对象:{"纽约":1," NewYork":3,"芝加哥":4}你可以添加另一个语句来打印出字符串形式,显然。

我们鼓励您逐步完成每个步骤的结果,并了解它的作用。