我可以用underscore.js做多个小组吗?

时间:2017-04-11 00:47:24

标签: javascript json underscore.js grouping

问题是我有一个没有育儿的json。所以我需要手动创建聚合;

这是我的json:

"data":[
    {"AREA":"A/M COMMON","DIVISION":"B","LOCATION":"FBC"},
    {"AREA":"A/M MAINTENANCE","DIVISION":"B","LOCATION":"FBC"},
    {"AREA":"A/M PRODUCTION LCD DIVISION","DIV":"B","LOCATION":"SONY"},
    {"AREA":"AM VIZIO MAINTENANCE","DIVISION":"B","LOCATION":"FBC"},
    {"AREA":"AM VIZIO PRODUCTION","DIVISION":"B","LOCATION":"VIZIO"},
    {"AREA":"BUSINESS PLANNING","DIVISION":"B","LOCATION":"FBC"},
    {"AREA":"COMARKET F/A PRODUCTION DIRECT","DIVISION":"B","LOCATION":"FBC"},
    {"AREA":"CONTROLLERS","DIVISION":"B","LOCATION":"FBC"},
    ]

我想将数据分为3个数组,首先是 LOCATION ,然后是 DIVISION ,最后是 AREA

我尝试使用underscore.js

    var groupedData = _.groupBy(data, function (d) { return d.LOCATION});

所以我想按层次结构进行分组,但这种方法只返回1次崩溃,我需要两次。

有没有办法可以做到这一点?我迷路了。

https://jsfiddle.net/jaelsvd/dwc5mdyL/

2 个答案:

答案 0 :(得分:1)

我认为这应该做你想要的:

let result = _.chain(data)
    .groupBy('AREA')
    .mapObject(area => _.groupBy(area, 'DIVISION'))
    .mapObject(area => _.mapObject(area, div => _.groupBy(div, 'LOCATION')))
    .value();

首先它由AREA分组,给出一个像:

这样的对象
{
    'AM/COMMON': [ /* AM/COMMON objects */ ],
    'A/M MAINTENANCE': [ /* A/M MAINTENANCE */ ],
    etc
}

然后它通过DIVISION'将每个对象映射到组。

最后,它将每个区域内的每个分区对象映射到LOCATION分组。

	let data = [
    {"AREA":"A/M COMMON","DIVISION":"B","LOCATION":"FBC"},
    {"AREA":"A/M MAINTENANCE","DIVISION":"B","LOCATION":"FBC"},
    {"AREA":"A/M PRODUCTION LCD DIVISION","DIV":"B","LOCATION":"SONY"},
    {"AREA":"AM VIZIO MAINTENANCE","DIVISION":"A","LOCATION":"FBC"},
    {"AREA":"AM VIZIO MAINTENANCE","DIVISION":"A","LOCATION":"FBC"},
    {"AREA":"AM VIZIO MAINTENANCE","DIVISION":"B","LOCATION":"FBC"},
    {"AREA":"AM VIZIO MAINTENANCE","DIVISION":"B","LOCATION":"FBX"},
    {"AREA":"AM VIZIO MAINTENANCE","DIVISION":"B","LOCATION":"FBX"},
    {"AREA":"AM VIZIO PRODUCTION","DIVISION":"B","LOCATION":"VIZIO"},
    {"AREA":"BUSINESS PLANNING","DIVISION":"B","LOCATION":"FBC"},
    {"AREA":"COMARKET F/A PRODUCTION DIRECT","DIVISION":"B","LOCATION":"FBC"},
    {"AREA":"CONTROLLERS","DIVISION":"B","LOCATION":"FBC"},
    ];

    let result = _.chain(data)
    	.groupBy('AREA')
    	.mapObject(area => _.groupBy(area, 'DIVISION'))
    	.mapObject(area => _.mapObject(area, div => _.groupBy(div, 'LOCATION')))
    	.value();
      
      console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

答案 1 :(得分:1)

Underscore有一种更简单的方法可以让它运行起来 @Jael Saavedra数据数组中的第3行有一个错误Div应该是DIVISION

使用此处的解决方案更新了您的jsfiddle https://jsfiddle.net/dwc5mdyL/3/

 var groupedData = _.groupBy(data, function(d) {
return d.LOCATION + "-" + d.DIVISION+ "-" + d.AREA;
});

原始资料来源 coderwall google cache