简体   繁体   中英

Sort object by key in descending order

This is simple yet most painful question for me.

Take an example of following snippet of code:

 const test = {}; test[2] = 'value2'; test[1] = 'value1'; console.log(test);

The result of above snippet is:

{
  1: "value1",
  2: "value2"
}

I want to pass this object as it is with following result:

{
  2: "value2",
  1: "value1"
}

PS: I tried Object.keys(test).sort() and Object.keys(test).reverse() and then chained it with function for re-creating the object but nothing seems to be working for me.

i check this you can use something like this to extend your key and values into another object

{key:"" , value:""}

 const test = {}; test[2] = 'value2'; test[1] = 'value1'; test[4] = 'value4'; var r = Object.keys(test).sort().reverse() console.log(r); var sorted ={} //look like JS Sorted this ASC r.forEach(k => { sorted[k] = test[k] }); console.log(JSON.stringify(sorted)); // So use Array var sorted =[] r.forEach(k => { sorted.push({"key":k ,"value": test[k]}) }); console.log(JSON.stringify(sorted));

It's not possible with positive integer keys. It may kind of work on most browsers (but probably not all) with non-positive integer keys : [-2] , [.2] , ['2 '] , etc.

 const obj = { '2 ': "value2", '1 ': "value1" }; console.log(obj); console.log( JSON.stringify(obj, 0, 2).replace(/ ": "/g, '": "') );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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