14

我有 2 个对象列表:

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 或其他外部库中)在这些上的一行中进行左连接?就像是:

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

我可以自己编写,但如果 LoDash 有优化版本,我想使用它。

4

8 回答 8

8

此实现使用 ES6 扩展运算符。同样,不是要求的库函数。

const leftJoin = (objArr1, objArr2, key1, key2) => objArr1.map(
    anObj1 => ({
        ...objArr2.find(
            anObj2 => anObj1[key1] === anObj2[key2]
        ),
        ...anObj1
    })
);
于 2019-04-11T23:56:19.087 回答
5

您可以使用Alasql JavaScript SQL 库来连接两个或多个对象数组:

var res = alasql('SELECT people.name AS person_name, cars.name, cars.color \
    FROM ? people LEFT JOIN ? cars ON people.carid = cars.id',[people, cars]);

在 jsFiddle试试这个例子。

于 2014-12-18T03:50:26.490 回答
5

Linq.js http://linqjs.codeplex.com/将与许多其他事情一起进行连接

于 2013-07-26T11:47:59.280 回答
4

使用 underscore.js 实现并不难

function leftJoin(left, right, left_id, right_id) {
    var result = [];
    _.each(left, function (litem) {
        var f = _.filter(right, function (ritem) {
            return ritem[right_id] == litem[left_id];
        });
        if (f.length == 0) {
            f = [{}];
        }
        _.each(f, function (i) {
            var newObj = {};
            _.each(litem, function (v, k) {
                newObj[k + "1"] = v;
            });
            _.each(i, function (v, k) {
                newObj[k + "2"] = v;
            });
            result.push(newObj);
        });
    });
    return result;
}

leftJoin(people, cars, "carid", "id");
于 2013-07-27T14:52:36.850 回答
2

不,LoDash 没有加入,但很容易实现你自己的,这不是一个加入,而是选择所有拥有匹配汽车的人:

    var peopleWithCars = _.filter(people, function (person) {
        return _.exists(cars, function(car) {
            return car.id === person.id;
        });
    });
于 2014-08-25T05:48:10.067 回答
2

你可以用纯 JavaScript 做这样的事情。

people.map(man => 
        cars.some(car => car.id === man.carid) ? 
            cars.filter(car => car.id === man.carid).map(car => ({car, man})) : 
            {man}
        ).reduce((a,b)=> a.concat(b),[]);
于 2018-03-03T04:43:11.787 回答
0

这个例子使用Lodash 左连接第一个匹配的对象。不完全是问题的要求,但我发现类似的答案很有帮助。

var leftTable = [{
  leftId: 4,
  name: 'Will'
}, {
  leftId: 3,
  name: 'Michael'
}, {
  leftId: 8,
  name: 'Susan'
}, {
  leftId: 2,
  name: 'Bob'
}];

var rightTable = [{
  rightId: 1,
  color: 'Blue'
}, {
  rightId: 8,
  color: 'Red'
}, {
  rightId: 2,
  color: 'Orange'
}, {
  rightId: 7,
  color: 'Red'
}];

console.clear();

function leftJoinSingle(leftTable, rightTable, leftId, rightId) {
  var joinResults = [];

  _.forEach(leftTable, function(left) {
  	      var findBy = {};
      findBy[rightId] = left[leftId];

      var right = _.find(rightTable, findBy),
          result = _.merge(left, right);

      joinResults.push(result);
  })

  return joinResults;
}


var joinedArray = leftJoinSingle(leftTable, rightTable, 'leftId', 'rightId');
console.log(JSON.stringify(joinedArray, null, '\t'));

结果

[
	{
		"leftId": 4,
		"name": "Will"
	},
	{
		"leftId": 3,
		"name": "Michael"
	},
	{
		"leftId": 8,
		"name": "Susan",
		"rightId": 8,
		"color": "Red"
	},
	{
		"leftId": 2,
		"name": "Bob",
		"rightId": 2,
		"color": "Orange"
	}
]

于 2016-03-31T13:52:56.127 回答
-1

这是我为 Javascript(在本例中为 JQuery)执行的一个简单循环,用于在 someID 上“加入”obj1 和 obj2,并将一个属性从 obj2 添加到 obj1。

如果你想做一个更完整的连接,你可以通过并扩展它以循环 obj2.hasOwnProperty() 并复制它。

    $.each(obj1,function(i){
        $.each(obj2, function(k){
            if (obj2[k].someID == obj1[i].someID ){
                obj1[i].someValue = obj2[k].someValue;
            }
        });
     });
于 2015-01-06T18:50:24.973 回答