链接groupby和pluck

时间:2017-03-22 07:36:41

标签: underscore.js

data =[
{
    "origin": "Mumbai",
    "destination": "Chennai"
},
{
    "origin": "Mumbai",
    "destination": "Delhi",
},
{
    "origin": "Pune",
    "destination": "Brahmapur",
},]

期望的输出:

[
  {"Mumbai" : ["Chennai","Delhi"]},
  {"Pune" : ["Brahmapur"]}
]

以下是我要做的事情:

var list = _.pluck(data, 'destination'); // it gives the array of destinations
var gList = _.groupBy(data, 'origin'); // it gives me json which are grouped by the origin key.

我尝试在下面结合使用 pluck groupby ,它会给我一些特定原始密钥的目标数组,但显然它不起作用。

var gpList = _.groupBy(_.pluck(data, 'parname'), 'category');

1 个答案:

答案 0 :(得分:1)

你几乎可以选择那些功能。

首先要做的是groupBy来源。这将返回一个如下所示的对象:

{
    Mumbai: [ { origin: 'Mumbai', destination: 'Chennai' },
              { origin: 'Mumbai', destination: 'Delhi' } ],

    Pune: [ { origin: 'Pune', destination: 'Brahmapur' } ]
}

然后使用mapObjectpluck目的地:

var result = _.chain(data)
    .groupBy('origin')
    .mapObject(group => _.pluck(group, 'destination'))
    .value()