在 Javascript 中加入 [英] Joins in Javascript
本文介绍了在 Javascript 中加入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有 2 个对象列表:
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"}];
是否有一个函数(可能在 Angular、JQuery、Underscore、LoDash 或其他外部库中)可以在一行中进行左连接?类似的东西:
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");
我可以自己编写,但如果 LoDash 有优化版本,我想使用它.
I can write my own, but if LoDash has an optimised version I'd like to use that.
推荐答案
此实现使用 ES6 展开运算符.同样,不是所要求的库函数.
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
})
);
这篇关于在 Javascript 中加入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文