javascript - JS-JSON : adding a keypair in each object by calculating the difference in time now and a timestamp in the JSON object

标签 javascript arrays json

我想在 JSON 数组的每个对象中存储一个额外的 key 对并计算出时间。

我有一个包含对象的 JSON 数组,如下所示:

var arrofobj = [{"id": 1, "timestamp":1545311087282},{"id": 2, "timestamp":1545311148254}];

我想向数组中的每个对象添加一个 key 对,其中包含“现在时间戳”与 JSON 对象中存储的时间戳之间的差异。

它可以与 forEach() 语句一起使用吗,我可以在其中使用如下语句生成新的 key 对: arrofobj.timestampdiff = (new Date().getTime() - arrofobj.timestamp)

但我不知道如何?

此外,我想计算存储的时间戳以分钟为单位的差异,现在,有时存储的时间戳是0,那么它也必须报告0?

最佳答案

您可以按如下方式使用Array.forEach

var arrofobj = [{"id": 1, "timestamp":1545311087282},{"id": 2, "timestamp":1545311148254}];
let now = new Date().getTime();
arrofobj.forEach(v => v.timestampdiff = now - v.timestamp);
console.log(arrofobj);

关于javascript - JS-JSON : adding a keypair in each object by calculating the difference in time now and a timestamp in the JSON object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53869448/

相关文章:

arrays - Icarus verilog 转储内存数组 ($dumpvars)

java - 我应该使用什么数据结构来存储java中的二进制代码?

javascript - 将大型 JSON 对象的值提取到另一个对象中

javascript - 合并两个对象并重命名相同的属性

c - 为什么函数必须返回 char * 而不是 char 数组?

javascript - 在 php 中解释 json 并将其传递给 mysql 时遇到问题

java - GSON:使用 gson.toJson 将 Java 对象转换为 JSON 时缺少字段

javascript - JavaScript 中事件处理程序的异步或同步调用

javascript - 公共(public)文件夹中的 Laravel CSS 和 JS 显示 404 错误

c# - Window Phone 7/8如何读取本地.json文件并显示数据?