Let's assume that we have 2 sets of objects
set1 = [{'id':'1', 'x':'1', 'y':'2'}, {'id':'2', 'x':'2', 'y':'2'}]
set2 = [{'id':'1', 'z':'1'}, {'id':'2', 'z':'2'}]
We want:
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?
Another option using Ramda:
assumptions
Output
I guess a better output might be (shouldn't be hard to get here):
and add support for inner joins. But I was replacing some crappy code and needed to replicate the object hierarchy.
OPTION 1, plain js
I would suggest that you transform each of the lists into a set by id, e.g.
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.
OPTION 2, underscore, for dense id sets, using _.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.OPTION 3, underscore, using _.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
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).
OPTION 4: Alasql library
Alasql can join two tables in 'SQL manner'.:
It gives exactly what you need:
Try this example in jsFiddle.