简体   繁体   English

如何在 react.js 中按日期订购一个 Object.keys 数组?

[英]how to order by date one Object.keys array in react.js?

my object:我的 object:

0: {
    id: 20050,
    name: "something",
    date: "2021-01-28 16:46:02",
},
1: {
    id: 20054,
    name: "other something",
    date: "2021-01-28 12:25:57",
},
2: {
    id: 20059,
    name: "again something",
    date: "2021-02-15 07:01:34",
},

I map it like this:我 map 是这样的:

Object.keys(myObj).forEach(function(item, index) {
    myObj[item].id // returns myObj id value
    myObj[item].name // returns myObj name value
});

I need to sort by the most recent or oldest date , and I have no idea how to use "myObj.sort" with the type of object I have here我需要按最近或最旧的日期排序,但我不知道如何将“myObj.sort”与我这里的 object 类型一起使用

Convert your object to array for sorting and then revert back.将您的 object 转换为数组进行排序,然后恢复。

 const obj = { 0: { id: 20050, name: 'something', date: '2021-01-28 16:46:02' }, 1: { id: 20054, name: 'other something', date: '2021-01-28 12:25:57' }, 2: { id: 20059, name: 'again something', date: '2021-02-15 07:01:34' } }; // convert obj to arr const values = Object.values(obj); // sort by date values.sort((a, b) => new Date(b.date) - new Date(a.date)); // convert arr to obj const res = {...values }; console.log(res);

This will convert the dates into a parseable form (by replacing the space with a T so that it ends up YYYY-MM-DDTHH:MM:SS ) and then sort them:这会将日期转换为可解析的形式(通过用 T 替换空格,使其以YYYY-MM-DDTHH:MM:SS ),然后对它们进行排序:

let result = Object.values(myObj).sort((a,b) => 
 new Date(b.date.replace(" ","T")) - new Date(a.date.replace(" ","T"))
)

This does get rid of the initial object keys (0,1,2,etc), which I'm assuming you don't need since they have individual IDs, but if you did need them, you could copy them into the object structure first before sorting.这确实摆脱了最初的 object 键(0、1、2 等),我假设您不需要它们,因为它们具有单独的 ID,但如果您确实需要它们,您可以将它们复制到 object 结构中首先在排序之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM