首页 > 解决方案 > 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'
  },
  ....
]

标签: javascriptnode.jsjson

解决方案


该代码存在三个问题:

  1. 您正在使用该date属性,但该示例使用 name timestamp

  2. timestamp值是字符串。构造Date函数查看您传递给它的参数的类型,并对字符串和数字执行不同的操作。您想先将它们转换为数字(然后乘以 1000,从秒转换为毫秒)。Date(但如果您只是比较它们,则没有必要。)

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

显然,您必须将字符串格式调整为所需的格式。唯一的内置格式是toStringand toISOString,否则你必须自己动手或使用像 Moment 这样的库。


推荐阅读