我想在 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/