简体   繁体   English

在node.js中合并对象

[英]Combine objects in node.js

My node.js app receives two json objects from external API. 我的node.js应用程序从外部API接收两个json对象。 The first object is weather data by days where the keys are unix timestamp: 第一个对象是按天数的天气数据,其中的键是Unix时间戳记:

{
  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): 第二个对象是这几天的小时数天气(如果上面的对象有3天,则此对象中有3 * 24个键):

{
  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. 我认为使用Transform Stream这样做会很好,但不知道如何正确执行。 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. 我想知道的主要事情是如何在不给事件循环施加太大压力的情况下合并两个对象。

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. 如果可以假设每天总有24个数据点,则可以使用Object.keys()获取日期和小时的时间戳数组并对其进行排序。 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. 然后,您可以将第一天的时间戳记与前24小时时间戳记匹配,将第二天的时间戳记与第二组24小时时间戳记匹配,依此类推。

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. 如果您还需要更多,请随时询问,我将编辑答案。

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

Combine objects 合并物件

If you using es5, Object.assign({}, obj1, obj2); 如果使用es5,则Object.assign({}, obj1, obj2);

or you using es6 or above standard, use spread operator to combine your objects 或者您使用的是es6或更高标准,请使用散布运算符组合您的对象

Ex const obj1 = { a: 1 }; const obj2 = { b: 2 }; const data = { ...obj1, ...obj2 }; Ex const obj1 = { a: 1 }; const obj2 = { b: 2 }; const data = { ...obj1, ...obj2 }; 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. 使用三点(...)扩展您的属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM