Skip to content

Instantly share code, notes, and snippets.

@aire-con-gas
Created June 15, 2018 05:30
Show Gist options
  • Select an option

  • Save aire-con-gas/016c7b46421b5e633ba4a531b3c8ccd3 to your computer and use it in GitHub Desktop.

Select an option

Save aire-con-gas/016c7b46421b5e633ba4a531b3c8ccd3 to your computer and use it in GitHub Desktop.
Flatten nested object
function flatten(obj, key_id = '') {
let newObj = {};
const keyPrefix = key_id + (key_id !== '' ? '.' : '');
for(let key in obj) {
if (typeof obj[key] === 'object') {
newObj = Object.assign({}, newObj, flatten(obj[key], key));
} else {
newObj[keyPrefix + key] = obj[key];
}
}
return newObj;
}
const start = {
a: 'b',
c: {
d: 'e',
f: 'g',
h: {
i: 'j',
k: 'l',
m: {
n: 'o'
}
}
},
p: 'q'
};
console.log('flatten', flatten(start));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment