javascript - Node Js根据unix时间戳对Json对象进行排序
问题描述
我有以下 json 对象:
var my_array = [
{
timestamp: '1571967208',
transaction: 'DEPOSIT',
name: 'Bob',
amout: '10'
},
{
timestamp: '1571967200',
transaction: 'DEPOSIT',
token: 'Roy',
amount: '60'
},
{
timestamp: '1571967189',
transaction: 'WITHDRAWAL',
token: 'Bob',
amount: '10'
},
{
timestamp: '1571966982',
transaction: 'WITHDRAWAL',
token: 'bob',
amount: '50'
}
]
我正在尝试按时间戳(从最新到最后)对其进行排序并显示新数组,但时间戳以人类可读的格式显示,例如“2019 年 10 月 25 日,星期五,凌晨 1:33:28”。
我在我的程序中使用了以下代码:
function comp(a, b) {
return new Date(a.my_array .date).getTime() - new Date(b.my_array .date).getTime();
}
result.sort(comp);
但这不是排序是错误的还是有其他方法可以做到这一点?例如下面的新数组:
var my_array = [
{
timestamp: 'Friday, October 25, 2019 1:33:28 AM',
transaction: 'DEPOSIT',
name: 'Bob',
amout: '10'
},
....
]
解决方案
该代码存在三个问题:
您正在使用该
date
属性,但该示例使用 nametimestamp
。timestamp
值是字符串。构造Date
函数查看您传递给它的参数的类型,并对字符串和数字执行不同的操作。您想先将它们转换为数字(然后乘以 1000,从秒转换为毫秒)。Date
(但如果您只是比较它们,则没有必要。)您
a.my_array.date
在回调中使用等,但您要直接使用的是回调参数。
由于-
将隐式转换为数字,因此排序部分为:
function comp(a, b) {
return a.timetstamp - b.timestamp;
}
然后使用map
结果将其格式化timestamp
为字符串(或只是forEach
或任何其他形式的循环),将其转换为日期,如下所示:
var dt = new Date(entry.timestamp * 1000);
这是* 1000
因为 yoru 时间戳以秒为单位,但new Date
预计为毫秒。*
也将隐式转换为数字。
然后转换timestamp
成你喜欢的字符串。
这是一个使用示例toString
:
my_array = my_array.sort(comp);
my_array.forEach(function(entry) {
entry.timestamp = new Date(entry.timestamp * 1000).toString();
});
现场示例:
var my_array = [
{
timestamp: '1571967208',
transaction: 'DEPOSIT',
name: 'Bob',
amout: '10'
},
{
timestamp: '1571967200',
transaction: 'DEPOSIT',
token: 'Roy',
amount: '60'
},
{
timestamp: '1571967189',
transaction: 'WITHDRAWAL',
token: 'Bob',
amount: '10'
},
{
timestamp: '1571966982',
transaction: 'WITHDRAWAL',
token: 'bob',
amount: '50'
}
];
function comp(a, b) {
return a.timetstamp - b.timestamp;
}
my_array = my_array.sort(comp);
my_array.forEach(function(entry) {
entry.timestamp = new Date(entry.timestamp * 1000).toString();
});
console.log(my_array);
显然,您必须将字符串格式调整为所需的格式。唯一的内置格式是toString
and toISOString
,否则你必须自己动手或使用像 Moment 这样的库。
推荐阅读
- c++ - 对 boost::serialization 的未定义引用
- vue.js - 如何在 Vue 3 组件中使用 Vuex 4 状态数据作为另一个调度的有效负载?
- android - 在 Android 中使用 Kotlin Coroutines 保存文件显示不适当的阻塞方法调用
- javascript - 使用给定条件验证字符串
- javascript - React 中的 Axios/Backend 会在一段时间后停止工作且没有错误
- c# - 带编码的 Asp net core 文件结果
- python - multiprocessing.Pipe() 返回的连接对象是否在不同进程中共享?
- kubernetes - “kubectl cluster-info”命令的输出
- r - 如何按数组中的对象将列拆分为行?
- r - ggplot2中的变音符号