Last active
June 16, 2020 09:45
-
-
Save FeMaffezzolli/e3db5010bac86973b6312104b444f852 to your computer and use it in GitHub Desktop.
Create a flatten object from an any level nested object.
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
/** | |
* Creates a flatten object from an any level nested object. | |
* | |
* @example | |
* | |
* Create following object: | |
* | |
* { | |
* 'address.city.name': 'São Paulo', | |
* 'address.state.name': 'SP', | |
* 'address.street.number': 123, | |
* 'address.street.name': 'Gustave Rapin', | |
* } | |
* | |
* From this object: | |
* | |
* { | |
* address: { | |
* city: { | |
* name: 'São Paulo' | |
* }, | |
* state: { | |
* name: 'SP' | |
* }, | |
* street: { | |
* number: 123, | |
* name: 'Gustave Rapin' | |
* } | |
* } | |
* } | |
* | |
* @param {object} input | |
* @param {string} divider | |
* @return {object} | |
*/ | |
export function flattenObject(input, divider = '.') { | |
const mapper = {} | |
const dive = (name, value) => { | |
if (typeof value !== 'object') { | |
mapper[name] = value | |
return | |
} | |
Object.keys(value).forEach((key) => | |
dive(`${name}${divider}${key}`, value[key]), | |
) | |
} | |
Object.keys(input).map((k) => dive(k, input[k])) | |
return mapper | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment