JavaScript objects cannot be sorted and reversed.If you are familiar with it, please let me know.
There is a function that returns the following objects, and I would like to reverse them in descending order.
The newly added data seems to be added below, but when I actually tried to sort it, there was no data such as date, so it didn't come in the new order, and functions such as reverse() seemed to be valid only for arrays and could not be applied to objects.
How can I reverse it?
objects of interest:
{
"0bf10e9f392d20bc5296df07c0087af8": {
"discount": "0",
"id": "xxxx",
"name": "nnnnnn",
"options":",
"price": "100",
"qty": "2",
"rowId": "0bf10e9f392d20bc5296df07c0087af8",
"subtotal": "100",
"tax": "0"
},
"0bf10e9f392d20b45464566df07c0087": {
"discount": "0",
"id": "xxxx",
"name": "nnnnnn",
"options":",
"price": "100",
"qty": "2",
"rowId": "0bf10e9f392d20b45464566df07c0087",
"subtotal": "100",
"tax": "0"
},
....
}
Previously, objects had no order.It has recently been added to the specification, but it is not very easy to use.Basically, it is better not to write code that uses the order of objects.
If you still want to.
First, get an array of keys (property names) such as Object.keys()
and flip them.Insert the results into the object.
Note: Property names that can be interpreted as numerical values are not in the order of insertion, so there is nothing we can do.
for(const key of Object.keys(origObj).reverse()){
newObj[key] = originObj [key]
}
If you want to change the object directly, erase it with delete
and reinsert it.However, IE should not be able to do this because the behavior when delete
is different.
for(const key of Object.keys(obj).reverse()){
constval=obj[key]
delete obj [key]
obj [key] = val
}
© 2024 OneMinuteCode. All rights reserved.