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

如何判断JavaScript对象含嵌套对象并递归获取所有键名

多层嵌套对象全键名递归获取实现

核心实现逻辑分4步:

  • 初始化空数组存储收集到的键名
  • 遍历当前对象层级的所有自有可枚举键,每遍历到一个键就存入结果数组
  • 校验当前键对应的值:如果是纯普通对象(排除null、数组等typeof判定为object但非普通键值对对象的特殊值),就递归执行键收集逻辑,把递归返回的子层键合并到总结果
  • 所有层级遍历完成后返回最终的键名数组

注意不要直接用typeof value === 'object'做嵌套判断:typeof null、typeof []的返回值都是object,会导致递归逻辑异常,建议用Object.prototype.toString做精准类型判断。

基础实现代码(返回所有层级的平铺键名)

// 校验值是否为普通键值对对象
const isPlainObject = (value) => {
  return Object.prototype.toString.call(value) === '[object Object]'
}

const getAllKeys = (targetObj) => {
  const collectedKeys = []
  // 遍历当前层所有自有键
  for (const key of Object.keys(targetObj)) {
    collectedKeys.push(key)
    const currentValue = targetObj[key]
    // 遇到嵌套对象则递归收集子层键
    if (isPlainObject(currentValue)) {
      collectedKeys.push(...getAllKeys(currentValue))
    }
  }
  return collectedKeys
}

// 测试用例
const spacing = {
  xxs: "0.25rem",
  xs: "0.5rem",
  sm: "0.75rem",
  md: "1rem",
  lg: "1.5rem",
  "2xl": "2rem",
  "3xl": "3rem",
  oggetto: {
    "1": 1,
    "2": 2,
  },
}

console.log(getAllKeys(spacing))
// 输出: ['xxs', 'xs', 'sm', 'md', 'lg', '2xl', '3xl', 'oggetto', '1', '2']

扩展:如果需要保留键的层级路径

如果需要区分子键所属的父节点,只需要给函数增加父路径前缀参数,即可返回带层级信息的键路径:

const getAllKeyPaths = (targetObj, parentPath = '') => {
  const collectedPaths = []
  for (const key of Object.keys(targetObj)) {
    const currentPath = parentPath ? `${parentPath}.${key}` : key
    collectedPaths.push(currentPath)
    const currentValue = targetObj[key]
    if (isPlainObject(currentValue)) {
      collectedPaths.push(...getAllKeyPaths(currentValue, currentPath))
    }
  }
  return collectedPaths
}

// 输出: ['xxs', 'xs', 'sm', 'md', 'lg', '2xl', '3xl', 'oggetto', 'oggetto.1', 'oggetto.2']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 00:33:31