如何根据时间戳对对象进行排序?

问题描述 投票:0回答:3

我有一个消息JSON对象,每个消息都有一个timeStamp提交时间。我想根据timeStamp对该对象进行排序。

例如:

"Messages": {
  "message1": {
    "msg"       : "I'm trying to make this work",
    "timeStamp" : "2018-02-15T06:24:44.12+00:00"
  },
  "message2": {
    "msg"       : "I really need your help SO!",
    "timeStamp" : "2018-03-01T13:57:27+00:00"  
  },
  "message3": {
    "msg"       : "Please assist me dude!",
    "timeStamp" : "2018-03-01T11:57:27+00:00"
  }
}

生成的timeStamp来自使用momentjsmoment().format();

问题是,我不确定如何基于该时间戳格式过滤对象。

我目前没有工作的例子,也无法想到更好的方法。

Why do I need this?

我正在使用此对象在两个人之间显示消息,但消息需要根据时间排序。

Can't you just change the format and make it simple?

不,因为,目前我的整个应用程序都基于该格式,并且更改它将导致更多问题。

Update

我忘了提到输出的格式必须是排序后的对象(最近的是第一项)

javascript sorting object timestamp momentjs
3个回答
0
投票

这会将最近排序的消息首先输出为数组...如果确实需要,可以重建对象。

const json = {
    "Messages": {
        "message1": {
            "msg"       : "I'm trying to make this work",
            "timeStamp" : "2018-02-15T06:24:44.12+00:00"
        },
        "message2": {
            "msg"       : "I really need your help SO!",
            "timeStamp" : "2018-03-01T13:57:27+00:00"  
        },
        "message3": {
            "msg"       : "Please assist me dude!",
            "timeStamp" : "2018-03-01T11:57:27+00:00"
        }
    }
}

const messageIds = Object.keys(json.Messages)

const messages = messageIds.map(id => json.Messages[id]).sort((a, b) =>
    a.timeStamp < b.timeStamp ? 1 : -1
)

console.log(JSON.stringify(messages, null, 4))

0
投票

您可以按如下方式恢复日期:如果您的消息在变量中:foo

foo =  {
  "message1": {
    "msg"       : "I'm trying to make this work",
    "timeStamp" : "2018-02-15T06:24:44.12+00:00"
  },
  "message2": {
    "msg"       : "I really need your help SO!",
    "timeStamp" : "2018-03-01T13:57:27+00:00"  
  },
  "message3": {
    "msg"       : "Please assist me dude!",
    "timeStamp" : "2018-03-01T11:57:27+00:00"
  }
}

然后,这将添加一个新的属性wihch你可以排序(日期时间)

foo = Object.keys(foo).map(key => { return Object.assign({}, foo[key], {datetime: new Date(foo[key].timeStamp)}) });

您可以按顺序获取消息,如下所示:

const sortedMessges = Object.keys(foo).map(key => foo[key]).sort((a, b) =>
    a.datetime< b.datetime ? 1 : -1)

0
投票

你可以sort然后map排序的数组。

var obj = {"Messages": {  "message1": {    "msg"       : "I'm trying to make this work",    "timeStamp" : "2018-02-15T06:24:44.12+00:00"  },  "message2": {    "msg"       : "I really need your help SO!",    "timeStamp" : "2018-03-01T13:57:27+00:00"    },  "message3": {    "msg"       : "Please assist me dude!",    "timeStamp" : "2018-01-01T11:57:27+00:00"  }}};

var result = Object.keys(obj.Messages)
                   .sort((a, b) => Date.parse(obj.Messages[a].timeStamp) - Date.parse(obj.Messages[b].timeStamp))
                   .map(k => ({ [k]: obj.Messages[k] }) );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
© www.soinside.com 2019 - 2024. All rights reserved.