Using the latest JS features, such as distributing objects and Object.entries , should be fairly simple:
function flatObj(obj, path = []) { let output = {}; Object.entries(obj).forEach(([ key, value ]) => { const nextPath = [ ...path, key ]; if (typeof value !== 'object') { output[nextPath.join('.')] = value; return; } output = { ...output, ...flatObj(value, nextPath) }; }); }
Note that this code is probably not the most optimal, as it copies an object every time we want to merge it. Consider it more as the essence of what it would look, rather than a complete and final decision.
source share