Last active
April 28, 2018 11:11
-
-
Save AoiYamada/42937c1aa44bddac31457ead59c73d33 to your computer and use it in GitHub Desktop.
DggMDwcLDgIEBQEABAMDCw
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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