You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按sort_order字段排序JavaScript对象且不修改原有键值对

报错原因

sort()是JavaScript数组专属的原型方法,仅支持数组类型调用。你当前使用的data是普通键值对象,本身不具备sort方法,因此会抛出类型错误。

另外需要注意:ES6标准之前JavaScript对象的属性不存在固定顺序,如果你有强顺序需求更推荐直接使用数组存储数据;如果确实需要排序后的对象结构,可以通过以下方式实现:

实现代码

// 提取对象的[键, 值]对数组,按sort_order排序
const sortedEntries = Object.entries(data).sort((entryA, entryB) => {
  return entryA[1].sort_order - entryB[1].sort_order
})

// 按排序后的顺序组装新对象
const sortedData = {}
sortedEntries.forEach(([key, value]) => {
  sortedData[key] = value
})

执行后得到的sortedData就是你预期的输出结构。

内容的提问来源于stack exchange,提问作者user8989878

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 20:36:01