问题
I have object contain data like this
const testData = {
"11": {
"data": {
"firstName": "firstName",
"lastName": "lastName"
}
},
"12": {
"data": {
"firstName": "firstName",
"lastName": "lastName"
}
},
"00": {
"data": {
"firstName": "firstName",
"lastName": "lastName"
}
},
"01": {
"data": {
"firstName": "firstName",
"lastName": "lastName"
}
},
"final": {
"data": {
"firstName": "firstName",
"lastName": "lastName"
}
}
}
i want to sort this data by object keys like 00, 01, 11, 12, final
i have tried like this but i can not achieve what i want.Any idea would be appreciate?
sorted = Object.keys(testData).sort().reduce((acc, key) => ({
...acc, [key]: testData[key]
}), {})
console.log(sorted)
回答1:
You cannot. The defined iteration order for JavaScript object keys is as follows:
- Numeric keys, in ascending numeric order. (this includes strings such as
"11"
, but not"01"
), THEN... - String keys which are not numeric, in order of insertion. THEN...
- Symbol keys, in order of their insertion.
As you can see, regardless of insertion order, numeric keys will always appear first in the iteration order, and always in their numeric order.
In your example, "11"
and "12"
will always end up first, regardless of what you do.
In general, relying on order with objects (which are essentially unordered dictionaries you access via key), is ill-advised. If order matters, you should be using an array. Alternatively, you can use a Map
.
回答2:
Try something like this:
sorted = Object.keys(testData).sort((a,b) => {
if (a < b) return -1;
if (a > b) return 1;
return 0;
});
console.log(sorted)
来源:https://stackoverflow.com/questions/56837426/sorting-data-by-object-keys-does-not-work-when-some-of-the-keys-are-numeric