Skip to content

Instantly share code, notes, and snippets.

@scottlepp
Created November 22, 2017 20:48
Show Gist options
  • Save scottlepp/ff8a9e1018a5c1728caaacf21ff0f8f6 to your computer and use it in GitHub Desktop.
Save scottlepp/ff8a9e1018a5c1728caaacf21ff0f8f6 to your computer and use it in GitHub Desktop.
deep flatten
function flatten(source, key) {
let it, index = 0;
const flattened = {};
const delim = key !== undefined ? '.' : '';
key = key || '';
if (typeof source === 'string') {
flattened[key] = source;
return flattened;
}
for (const prop in source) {
it = source[prop];
// STEP 2 - determine if the value property is an object, array, or value
if (Array.isArray(it)) {
// STEP 2.1 - it's an array, iterate over the array and get key for each obj
index = 0;
for (const obj of it) {
key = delim + prop + '.' + index;
Object.assign(flattened, flatten(obj, key));
index++;
}
} else if (typeof it === 'object' && it !== null) {
// STEP 2.2 - it's an object, traverse
Object.assign(flattened, flatten(it, key + delim + prop));
} else {
// STEP 2.3 - The leaf - set the value
flattened[key + delim + prop] = it;
}
}
return flattened;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment