Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.