Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joins in Javascript

I have 2 lists of objects:

people = 
[{id: 1, name: "Tom", carid: 1},
 {id: 2, name: "Bob", carid: 1},
 {id: 3, name: "Sir Benjamin Rogan-Josh IV", carid: 2}];

cars=
[{id: 1, name: "Ford Fiesta", color: "blue"},
 {id: 2, name: "Ferrari", color: "red"},
 {id: 3, name: "Rover 25", color: "Sunset Melting Yellow with hints of yellow"}];

Is there a function (possibly in Angular, JQuery, Underscore, LoDash, or other external library) to do a left join in one line on these? Something like:

peoplewithcars = leftjoin( people, cars, "carid", "id");

I can write my own, but if LoDash has an optimised version I'd like to use that.

like image 401
Crashthatch Avatar asked Jul 26 '13 11:07

Crashthatch


People also ask

How do you join a number array?

The arr. join() method is used to join the elements of an array into a string. The elements of the string will be separated by a specified separator and its default value is a comma(, ).

How do you join a split array?

How it works: First, split the title string by the space into an array by using the split() string method. Second, concatenate all elements in the result array into a string by using the join() method. Third, convert the result string to lower case by using the toLowerCase() method.

How do you join strings?

The join() method takes all items in an iterable and joins them into one string. A string must be specified as the separator.

What does .split do in JavaScript?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.


2 Answers

This implementation uses the ES6 spread operator. Again, not a library function as asked for.

const leftJoin = (objArr1, objArr2, key1, key2) => objArr1.map(
    anObj1 => ({
        ...objArr2.find(
            anObj2 => anObj1[key1] === anObj2[key2]
        ),
        ...anObj1
    })
);
like image 67
Ashley Wilson Avatar answered Oct 02 '22 02:10

Ashley Wilson


Linq.js http://linqjs.codeplex.com/ will do joins along with many other things

like image 41
Geoff Avatar answered Oct 02 '22 01:10

Geoff