Javascript.像SQL中那样联接2组对象的最佳方式? [英] Javascript. Optimal way to join 2 sets of objects like in SQL?

查看:25
本文介绍了Javascript.像SQL中那样联接2组对象的最佳方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有2组对象

set1 = [{'id':'1', 'x':'1', 'y':'2'}, {'id':'2', 'x':'2', 'y':'2'}]
set2 = [{'id':'1', 'z':'1'}, {'id':'2', 'z':'2'}]

我们想要:

set3 = set1.join(set2).on('id'); 

>> set3 
[{'id':'1', 'x':'1', 'y':'2', 'z':'1'},{'id':'2', 'x':'2', 'y':'2', 'z':'2'}]

什么是实现此功能的正确工具? 下划线 可以在这里提供帮助吗?

What's right tools for achieving this functionality? May underscore help here?

推荐答案

选项1 ,普通js

我建议您将每个列表按ID转换为一组,例如

I would suggest that you transform each of the lists into a set by id, e.g.

{1: {x: 1, y: 1}, 2: {x: 2, y: 2}}

然后对其中一个(或两个)集合运行a,并创建一个具有这两个属性的新字典-后者取决于您要查找的是内部联接还是外部联接.这应该导致大致线性的运行时,字典的javascript实现非常有效.

Then run a for over one (or both) of the sets and create a new dictionary with attributes from these two -- this latter bit depends on whether you're looking for the inner or the outer join. This should result in a roughly linear runtime, the javascript implementation of dictionaries is pretty efficient.

选项2 ,下划线,用于密集的ID集,使用_.zip()

OPTION 2, underscore, for dense id sets, using _.zip()

如果 id 相对密集,并且您希望进行外部联接,或者事先知道ID的集合完全相同,则另一种选择是将数据填充到三个数组中-每个属性一个,然后使用下划线的zip()方法.

If the id's are relatively dense and you'd like the outer join or know in advance that the sets of ids are exactly the same, another option is to stuff the data into three arrays -- one for each attribute and then use the underscore's zip() method.

选项3 ,下划线,使用_.groupBy()

OPTION 3, underscore, using _.groupBy()

使用自定义比较方法在您拥有的列表上运行_.groupBy()的另一种可能性,该方法还允许连接多个键.不过,由于直接结果将是形式为

A yet another possibility in to run _.groupBy() on the lists you have with a custom comparison method, that will also allow joining on multiple keys. Some simple postprocessing will be required, though, since the direct result will be a dictionary of the form

{1: [{'id':'1', 'x':'1', 'y':'2'}, {'id':'1', 'z':'1'}],
 2: [{'id':'2', 'x':'2', 'y':'2'}, {'id':'2', 'z':'2'}]}

后一种情况下的内部联接行为可以通过过滤出结果字典中那些列表中没有最大数目的项(在此示例中为2)来实现.

An inner join behaviour in the latter case can be achieved by filtering out those items in the resulting dictionary that don't have the maximum number of items in the list (2, in the example).

这篇关于Javascript.像SQL中那样联接2组对象的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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