背景:今天在做一个需求,前端把排好的顺序的数组,以JSON.stringify的格式传给后端,但是发现,传的顺序发现改变了。
代码:
const arr = [
{
index: 1,
name: 'zhangsan',
hobby: 'basketball'
},
{
index: 2,
name: 'lisi',
hobby: 'football'
},
{
index: 3,
name: 'wangwu',
hobby: 'music'
},
{
index: 4,
name: 'zhaoliu',
hobby: 'photo'
},
]
后端需要一个Json的一个字符串,然后JSON.stringify(arr);打印如下,顺序乱了。
const arr = [
{
index: 1,
name: 'zhangsan',
hobby: 'basketball'
},
{
index: 4,
name: 'zhaoliu',
hobby: 'photo'
},
{
index: 3,
name: 'wangwu',
hobby: 'music'
},
{
index: 2,
name: 'lisi',
hobby: 'football'
},
]
这是因为 JSON 标准规定,对象中的属性在 JSON 字符串中是无序的,属性的顺序不受控制。
解决方法:如果您希望保持对象属性的顺序不变,可以在转换为 JSON 字符串之前先对数组进行排序,确保属性按照您期望的顺序排列。
const sortArr = arr.sort((a, b) => a.index - b.index);
以此记录下这个坑。