function flattenObject(obj, prefix = '', result = {}) {
for (const [key, val] of Object.entries(obj)) {
const newKey = prefix ? `${prefix}.${key}` : key;
if (val && typeof val === 'object' && !Array.isArray(val)) {
flattenObject(val, newKey, result);
} else {
result[newKey] = val;
}
}
return result;
}
// Usage
const config = { db: { host: 'localhost', port: 5432 }, app: { name: 'MyApp' } };
console.log(flattenObject(config));
// { 'db.host': 'localhost', 'db.port': 5432, 'app.name': 'MyApp' }
Create a free account and build your private vault. Share publicly whenever you want.