Ajax返回自动排序的编号命名数组



因此,我遇到了一个问题,我的javascript是自动排序编号命名数组。

我的对象来自Ajax调用,所以我不能以不同的方式构建它。

我的问题示例:

var test = {"1": "test1", "0": "test2", "2": "test3"}

输出

console.log(test);
// {0: "teste2", 1: "teste1", 2: "teste3"}

订单应为1,0,2…

有什么办法解决这个问题吗?

顺便说一句,这是一个例子,在脚本中,我得到了一个抛出ajax的对象,当我console.log它时,它会自动排序,所以map((函数在这里不起作用。

对象并不总是保证密钥顺序。打印对象时属性的默认顺序如下:

  • 升序的类整数键
  • 按插入顺序排列的字符串键
  • 按插入顺序排列的符号

在下面的示例中,类整数键在控制台JSON结果中以数字方式排序。

const test = { "1": "test1", "0": "test2", "2": "test3" };
console.log(test); // {"0": "test2", "1": "test1", "2": "test3"}
.as-console-wrapper { top: 0; max-height: 100% !important; }

如果要保留键的顺序,则需要存储键的顺序并在自定义JSON字符串化函数内对条目进行排序时引用它。如果只想按值排序,这要简单得多,因为不需要键顺序数组。

const test = { "1": "test1", "0": "test2", "2": "test3" };
const keyOrder = [ 1, 0, 2 ];
// Sorted by referenced key order
const customJsonStr = (obj, indent = '  ') =>
`{n${Object.entries(obj)
.sort(([ka], [kb]) => keyOrder[ka] - keyOrder[kb])
.map(([k, v]) => `${indent}"${k}": "${v}"`).join(',n')}n}`
// Sorted by value only
const customJsonStr2 = (obj, indent = '  ') =>
`{n${Object.entries(obj)
.sort(([ka, va], [kb, vb]) => va.localeCompare(vb))
.map(([k, v]) => `${indent}"${k}": "${v}"`).join(',n')}n}`
console.log(customJsonStr(test));  // {"1": "test1", "0": "test2", "2": "test3"}
console.log(customJsonStr2(test)); // {"1": "test1", "0": "test2", "2": "test3"}
.as-console-wrapper { top: 0; max-height: 100% !important; }

console.log正在自动对输出进行排序,除非您调用高阶函数Array.prototype.sort,否则您的JavaScript数组本身不会被排序

最新更新