← 中文资源

简体中文版本

对象展平成点路径键

递归把嵌套对象压成点路径键的扁平表,unflatten 按点分段重建层级:数组保持为叶子值不展开,往返一次即可与原对象逐字段对齐。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

flat: { 'server.host': 'localhost', 'server.tls.enabled': true, port: 8080 }
arrays stay leaves: { tags: [ 'a', 'b' ] }
round trip equal: true

实现说明

全部逻辑都在函数 flattenObject、unflatten中。 迭代是嵌套的:for (const key of Object.keys(value)) 框定这一趟,for (const path of Object.keys(flat)) 做逐项处理。

使用要点

  • 跑完文件,输出里会留下标记——flat:、arrays stay leaves:、round trip equal:。

常见问题

除了语言运行时还需要什么准备?

什么都不需要——语言运行时是唯一要求。 文件在加载时定义 flattenObject、unflatten。

签名一览:function flattenObject(value, prefix, out)

核心语句

const config = { server: { host: 'localhost', tls: { enabled: true } }, port: 8080 };
const path = prefix ? prefix + '.' + key : key;
cursor[keys[keys.length - 1]] = flat[path];

代码示例

// Flatten nested objects into dotted key paths; arrays stay leaf values
function flattenObject(value, prefix, out) {
  prefix = prefix || '';
  out = out || {};
  for (const key of Object.keys(value)) {
    const path = prefix ? prefix + '.' + key : key;
    const item = value[key];
    if (item && typeof item === 'object' && !Array.isArray(item)) {
      flattenObject(item, path, out);
    } else {
      out[path] = item;
    }
  }
  return out;
}

function unflatten(flat) {
  const nested = {};
  for (const path of Object.keys(flat)) {
    const keys = path.split('.');
    let cursor = nested;
    for (const key of keys.slice(0, -1)) {
      cursor[key] = cursor[key] || {};
      cursor = cursor[key];
    }
    cursor[keys[keys.length - 1]] = flat[path];
  }
  return nested;
}

const config = { server: { host: 'localhost', tls: { enabled: true } }, port: 8080 };
const flat = flattenObject(config);
console.log('flat:', flat);
console.log('arrays stay leaves:', flattenObject({ tags: ['a', 'b'] }));
console.log('round trip equal:', JSON.stringify(unflatten(flat)) === JSON.stringify(config));