实现说明
全部逻辑都在函数 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));