当某些键是数字时,按对象键排序数据不起作用 [英] sorting data by object keys does not work when some of the keys are numeric

查看:50
本文介绍了当某些键是数字时,按对象键排序数据不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有对象包含这样的数据

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"
            }
        }
    }

我想按对象键(如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)

推荐答案

你不能.JavaScript 对象键的定义迭代顺序如下:

You cannot. The defined iteration order for JavaScript object keys is as follows:

  1. 数字键,按数字升序排列.(这包括诸如 "11" 之类的字符串,但 "01"),然后...
  2. 非数字的字符串键,按插入顺序排列.然后……
  3. 符号键,按插入顺序排列.
  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.

在您的示例中,"11""12"总是最先结束,无论您做什么.

In your example, "11" and "12" will always end up first, regardless of what you do.

一般来说,依赖对象的顺序(本质上是您通过键访问的无序字典)是不明智的.如果顺序很重要,您应该使用数组.或者,您可以使用 Map.

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.

这篇关于当某些键是数字时,按对象键排序数据不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆