Skip to content

Instantly share code, notes, and snippets.

@okerx
Last active September 17, 2021 15:45
Show Gist options
  • Save okerx/77f65ed717049461ca7a3768aa2737bf to your computer and use it in GitHub Desktop.
Save okerx/77f65ed717049461ca7a3768aa2737bf to your computer and use it in GitHub Desktop.
Convert nested Javascript object to dot notation object
const sample = {
a: 1,
b: {
x: 2,
y: 3,
z: 4,
},
c: {
x: 6,
y: 7,
z: {
i: 8,
j: 9,
k: {
foo: 10,
bar: 11,
extra: {
a: 12,
b: 13,
}
},
},
},
};
function flatObj(input, current) {
const root = {};
Object.keys(input).forEach(key => {
const _key = current ? `${current}.${key}` : key;
if (typeof input[key] !== 'object') {
root[_key] = input[key]
} else {
Object.keys(input[key]).forEach(subkey => {
if (typeof(input[key][subkey]) !== 'object') {
root[`${_key}.${subkey}`] = input[key][subkey];
} else {
const children = flatObj(input[key][subkey], `${_key}.${subkey}`)
Object.assign(root, children)
}
})
}
});
return root;
};
console.log(flatObj(sample))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment