Skip to content

Instantly share code, notes, and snippets.

@Aldizh
Created September 15, 2017 01:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Aldizh/aeaabd08d73ee068f7fc79e994c87c2e to your computer and use it in GitHub Desktop.
Save Aldizh/aeaabd08d73ee068f7fc79e994c87c2e to your computer and use it in GitHub Desktop.
Utility function to transform an object to flat key value pairs. It is used to maintain a mapping between an object structure and a general purpose file which could be translated for example.
/*
*
* Flattens an object given a nested object structure
* @function flattenObject
* @param {Object} obj - The object whose values and keys you want to map over.
* @return {String} - A json string with key-value pairs.
* @example
* const original = {
* address: {
* 'addressLine1': 'Address (Line 1)',
* 'addressLine2': 'Address (Line 2)',
* 'region': 'State / Region / Province',
* },
* location: {
* list: {
* 'name': 'NAME',
* 'noData': 'No Locations Available!',
* },
* },
* ...
* }
* const transformed = flattenObject(original)
* // Produces this result:
* {
* address.addressLine1: "Address (Line 1)"
* address.addressLine2: "Address (Line 2)"
* address.region: "State / Region / Province"
* location.list.name: "NAME"
* location.list.noData: "No Locations Available!"
* }
*
*/
const flattenObject = (obj) => {
const final = {}
let flatObject = {}
Object.keys(obj).forEach((o) => {
if (typeof obj[o] === 'object') {
flatObject = flattenObject(obj[o])
Object.keys(flatObject).forEach((x) => {
if (!flatObject.hasOwnProperty(x)) return
final[`${o}.${x}`] = flatObject[x]
})
} else { final[o] = obj[o] }
})
return final
}
export default flattenObject
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment