Joins in Javascript

后端 未结 8 2243
醉话见心
醉话见心 2020-12-14 03:31

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\", car         


        
相关标签:
8条回答
  • 2020-12-14 04:32

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

    0 讨论(0)
  • 2020-12-14 04:33

    This example uses Lodash to left join the first matched object. Not quite what the question asks, but I found a similar answer helpful.

    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'));

    Results

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

    0 讨论(0)
提交回复
热议问题