user3522457
user3522457

Reputation: 2963

complex grouping and merging array as properties

I wish to put an array into other's array as proproties by matching their common properties. I want jobDetails's uId to match with job's uId. Possible?

var job = [{
    "uId": 1
}, {
    "uId": 2
}]

var jobDetails = [{
    "uId": 1,
    "salary": 5000
}, {
    "uId": 2,
    "salary": 5000
}]

is it possible to produce something like

var job = [{
    "uId": 1,
    "salary": [{
        "uId": 1,
        "salary": 5000
    }]
}, {
    "uId": 2,
    "salary": [{
        "uId": 2,
        "salary": 5000
    }]

}];

Upvotes: 0

Views: 58

Answers (3)

sshet
sshet

Reputation: 1160

Yes possible , you need to play with both json objects

  var array = [];
  var object = {}
  $.each( job, function ( k , kal ) {

     $.each( jobDetails , function ( i , val) {
      object.uId = i;
      object.salary = val;
     });
     array.push(object);
});

console.log(JSON.stringify(array));

Upvotes: 0

Trace
Trace

Reputation: 18889

This is not a pure javascript solution, but I like to use underscore.js for this kind of typical actions on collections:

http://jsfiddle.net/FPwq7/

var finalCollection = []; 
_.each(job, function(model){ 
    var obj = _.findWhere(jobDetails, {uId: model.uId}); 
    _.extend(model, {'salaray': obj}); 
    finalCollection.push(model); 
}); 

console.log(finalCollection); 

I found that this Javascript utility belt takes care of some heavy lifting, and it makes the code a bit more pleasant to read than reading dry loops.

Upvotes: 0

Mihai Matei
Mihai Matei

Reputation: 24276

You may try something like this: http://jqversion.com/#!/XWFtbQb

for (var i = 0; i < job.length; i++) {
  for (var j = 0; j < jobDetails.length; j++) {
    if (job[i].uId == jobDetails[j].uId) {
      job[i].salary = jobDetails[j];
    }
  }
}

console.log(job);

Upvotes: 2

Related Questions