sorting data by object keys does not work when some of the keys are numeric [duplicate]

◇◆丶佛笑我妖孽 提交于 2021-02-10 14:21:14

问题


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:

  1. Numeric keys, in ascending numeric order. (this includes strings such as "11", but not "01"), THEN...
  2. String keys which are not numeric, in order of insertion. THEN...
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!