Search code examples
javascriptfor-loopforeachfor-in-loop

Javascript for/in loop - join items from two different objects?


I have these datasets below and I want to joint the data in each set:

    var data = {};
    var datasets = [
        {"_id":"58d6c806d7c80d5d44a35204","particles":{"timestamp":[1490470918708,1490470962915,1490470967186],"Particles":["108","108","109"]}},
        {"_id":"58d6caf62552b75f26f56f91","particles":{"timestamp":[1490471670888,1490473309103],"Particles":["109","100"]}}
    ];

    datasets.forEach(function(dataset, index) {
        for (var key in dataset.particles) {
            data[key] = dataset.particles[key];
        }
    });
    console.log(data);

Result:

{ timestamp: [ 1490471670888, 1490473309103 ],
  Particles: [ '109', '100' ] }

They are not joined. The result I am after:

 { timestamp: [ 1490470918708,1490470962915,1490470967186, 1490471670888, 1490473309103 ],
  Particles: [ '108','108','109', '109', '100' ] }

Any ideas?

EDIT

Is concat or push faster when comes to a very large data?


Solution

  • You have to concatanate the arrays, not just reassign the value.

    var data = {};
    var datasets = [
        {"_id":"58d6c806d7c80d5d44a35204","particles":{"timestamp":[1490470918708,1490470962915,1490470967186],"Particles":["108","108","109"]}},
        {"_id":"58d6caf62552b75f26f56f91","particles":{"timestamp":[1490471670888,1490473309103],"Particles":["109","100"]}}
    ];
    
    datasets.forEach(function(dataset, index) {
      for (var key in dataset.particles) {
    
        // Check if key already exists.
        if( data[key] === undefined )
          data[key] = [];
    
        // Add current timestamps.
        data[key] = data[key].concat(dataset.particles[key]);
      }
    });
    console.log(data);