下划线,嵌套分组依据并生成JSON [英] Underscore, Nested Group By and Generate a JSON

查看:114
本文介绍了下划线,嵌套分组依据并生成JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含重复对象的数组,我试图获得一个唯一的列表,其中唯一性是由对象属性的子集定义的.例如,

I have an array of objects with duplicates and I'm trying to get a unique listing, where uniqueness is defined by a subset of the properties of the object. For example,

当前JSON对象:

[{"x":6811,"y":15551,"a":"a"},
{"x":6811,"y":15551,"a":"b"},
{"x":6811,"y":15551,"a":"c"},
{"x":6811,"y":15552,"a":"c"},
{"x":6812,"y":15551,"a":"c"}]

如何按两个属性分组

最后一个结果是

[{"x":6811,"y":15551,"a":["a","b","c"]},
{"x":6811,"y":15552,"a":["c"]},
{"x":6812,"y":15551,"a":["c"]}]

如何使用下划线使其唯一并生成合并"a"键

How to use underscore to make it unique and generate a merge "a" Key

推荐答案

您可以使用groupByxy上创建复合键.然后,使用map遍历分组的数据.

You can use groupBy to create a composite key on x and y. Then, use map to iterate through the grouped data.

var data = [{"x":6811,"y":15551,"a":"a"},{"x":6811,"y":15551,"a":"b"},{"x":6811,"y":15551,"a":"c"},{"x":6811,"y":15552,"a":"c"},{"x":6812,"y":15551,"a":"c"}]
var groups = _.groupBy(data, ({x,y}) => `${x}_${y}`);
var result = _.map(groups, o => ({...o[0], a : _.pluck(o,'a')}));
console.log(result);

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

这篇关于下划线,嵌套分组依据并生成JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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