Stas Coder
Stas Coder

Reputation: 347

Combine objects in node.js

My node.js app receives two json objects from external API. The first object is weather data by days where the keys are unix timestamp:

{
  1491368400: /*some data*/,
  1491454800: /*some data*/,
  1491541200: /*some data*/,
}

The second object is weather by hours for these days (if there are three days in object above, there are 3 * 24 keys in this object):

{
  1491368400: /*some data*/,
  1491372000: /*some data*/,
  1491375600: /*some data*/,
  .............................
  /* there are 72 keys, 24 for every proper day from object above */
}

I need to combine these two objects: take data from second object with hours and calculate average values for each day from first object and put these values into the first object. I think it would be good to do it with Transform Stream, but have no idea how to do it properly. I need just a schema how to do it, not detailed solution.

UPDATE

The main thing I want to know is how to merge two objects without putting much pressure on event loop.

Upvotes: 0

Views: 939

Answers (3)

Kumar Albert
Kumar Albert

Reputation: 280

Combine objects

If you using es5, Object.assign({}, obj1, obj2);

or you using es6 or above standard, use spread operator to combine your objects

Ex const obj1 = { a: 1 }; const obj2 = { b: 2 }; const data = { ...obj1, ...obj2 };

// Now data value is { a: 1, b: 2 } 
// if keys are same , obj2 override obj1 value` 

Using triple dots(...) to spread your properties.

Upvotes: 0

William
William

Reputation: 751

Object.assign()

Can be used for this. It merges all argument objects to the first argument. If you don't want to modify your start objects, do:

Object.assign({}, obj1, obj2);

Upvotes: 1

Steve Hawkins
Steve Hawkins

Reputation: 120

If you can assume that you will always have 24 data points for every day, you could use Object.keys() to get an array of the timestamps for both the days and hours and order them. Then you can match the first day timestamp with the first 24 hour timestamps, second day with the second set of 24 hour timestamps, etc.

Due to your request for a direction and not code, I'll leave the rest up to you. If you need more though, please don't hesitate to ask and I'll edit the answer.

Upvotes: 0

Related Questions