我有一个消息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来自momentjs
使用moment().format();
。
问题是,我不确定如何基于该时间戳格式过滤对象。
我目前没有工作实例,也无法想到更好的方法。
我正在使用此对象在两个人之间显示消息,但消息需要根据时间排序。
不,因为目前我的整个应用程序都基于该格式,更改它会导致更多问题。
我忘了提到输出的格式必须是排序后的对象(最近的是第一项)
答案 0 :(得分: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))
答案 1 :(得分: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"
}
}
然后,这将添加一个新的属性,您可以对其进行排序(日期时间)
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)
答案 2 :(得分: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);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;