Skip to content

Instantly share code, notes, and snippets.

@AoiYamada
Last active April 28, 2018 11:11
Show Gist options
  • Save AoiYamada/42937c1aa44bddac31457ead59c73d33 to your computer and use it in GitHub Desktop.
Save AoiYamada/42937c1aa44bddac31457ead59c73d33 to your computer and use it in GitHub Desktop.
DggMDwcLDgIEBQEABAMDCw
'use strict';
/**
* Deep object flattener
* flatten an object, the message will be pull out, array index/nested key will be chained to be a new key.
* @param {object} obj - the target object
* @param {string} [prefix = ''] - the prefix of each key
* @return {object} flattened object
*/
function deepFlatten(obj, prefix = '') {
const result_obj = Object.create(null);
Object.keys(obj).forEach(key => {
const val = obj[key];
if (val.message) {
result_obj[prefix + key] = val.message;
} else if (!Array.isArray(val)) {
// pull out the nested layer
Object.assign(result_obj, deepFlatten(val, `${key}.`));
} else {
val.forEach((nested_val, index) => {
// pull out the nested layer
Object.assign(result_obj, deepFlatten(nested_val, `${key}[${index}].`));
});
}
});
return result_obj;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment