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

如何将嵌套对象扁平化为以下划线分隔路径为键的新对象?

扁平化嵌套对象为路径键形式

我完全理解你的需求——把嵌套对象的所有叶子节点转换成以下划线连接的路径作为键的扁平对象。递归确实是处理这种嵌套结构的正确思路,可能你之前的实现没处理好终止条件或者路径拼接的细节,我来给你一个可靠的JavaScript实现方案:

首先,先明确你的输入对象:

const originalObj = { 
  test: { 
    a1: { b1: "someText" }, 
    a2: 2, 
  }, 
  test2:{ 
    a3:3, 
    a4:{ "b4": "otherText", "b5": "textText" } 
  } 
};

下面是递归实现的扁平化函数:

function flattenObject(obj, parentPath = '') {
  const result = {};

  for (const key in obj) {
    // 只处理对象自身的属性,跳过继承来的属性
    if (obj.hasOwnProperty(key)) {
      // 拼接当前键的完整路径:父路径存在则用下划线连接,否则直接用当前键
      const currentPath = parentPath ? `${parentPath}_${key}` : key;
      const value = obj[key];

      // 判断当前值是否是需要递归处理的嵌套对象(排除null和数组)
      if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
        // 递归处理子对象,并将结果合并到当前结果中
        Object.assign(result, flattenObject(value, currentPath));
      } else {
        // 叶子节点直接存入结果
        result[currentPath] = value;
      }
    }
  }

  return result;
}

使用示例

调用这个函数后,就能得到你想要的输出:

const flattenedObj = flattenObject(originalObj);
console.log(flattenedObj);

输出结果:

{
  test_a1_b1: 'someText',
  test_a2: 2,
  test2_a3: 3,
  test2_a4_b4: 'otherText',
  test2_a4_b5: 'textText'
}

一些细节说明

  • 函数里用hasOwnProperty确保只处理对象自身的属性,避免意外处理原型链上的继承属性;
  • 加入了对null和数组的判断:如果你的场景里需要处理数组,可以修改判断逻辑,比如把数组元素的索引加入路径(比如test_array_0这样的形式);
  • 递归的终止条件是遇到非对象类型的叶子节点,直接将路径和值存入结果对象。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:32:51