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

如何按Object的值类型对其键自定义排序,而非按值本身排序

实现方案

核心实现逻辑:

  • 定义类型优先级权重,按需求顺序string > int > array > object分配从小到大的权重值,排序时权重越小越靠前
  • 单独处理类型判断逻辑,区分普通对象和数组(JS中typeof检测数组返回值为object,需用Array.isArray单独校验)
  • 提取原对象键值对数组,按值对应的类型权重排序后重新构造为新对象,ES6+环境下对象会保留插入顺序,符合需求

代码实现

function sortObjectByValueType (originObj) {
  // 类型优先级映射,数值越小排序越靠前
  const PRIORITY = {
    string: 0,
    number: 1,
    array: 2,
    object: 3
  }

  // 获取值的类型标签
  const getType = (val) => {
    if (typeof val === 'string') return 'string'
    // 严格校验整数可替换为:if (typeof val === 'number' && Number.isInteger(val))
    if (typeof val === 'number') return 'number'
    if (Array.isArray(val)) return 'array'
    if (typeof val === 'object' && val !== null) return 'object'
    // 其他类型可自行补充优先级,默认放到最后
    return 'other'
  }

  // 排序后生成新对象
  const sortedEntries = Object.entries(originObj).sort((entryA, entryB) => {
    return PRIORITY[getType(entryA[1])] - PRIORITY[getType(entryB[1])]
  })

  return Object.fromEntries(sortedEntries)
}

测试用例

const input = {"key4": {"name":"joe"},"key3": ["aaa", "bbb"],"key5": {"aaa":["name","joe"]}, "key1": "TypeString", "key2": 0}
const output = sortObjectByValueType(input)
console.log(output)
// 输出结果:{"key1":"TypeString","key2":0,"key3":["aaa","bbb"],"key4":{"name":"joe"},"key5":{"aaa":["name","joe"]}}

注意事项

  • 该实现依赖ES6+的Object.entries和Object.fromEntriesAPI,低版本运行环境可引入对应polyfill兼容
  • 若存在null、boolean、undefined等其他未覆盖类型,可自行在PRIORITY映射中补充对应优先级规则
  • 同类型的键会保留在原对象中的相对顺序,JS内置的sort方法为稳定排序,不会打乱同权重元素的原有位置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 08:18:03