Created
September 15, 2017 01:32
-
-
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.
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
/* | |
* | |
* 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