Created
July 27, 2024 02:10
-
-
Save RodrigoNovais/8c2b9d7c2003af93d9b7f9cd7ba8ceeb to your computer and use it in GitHub Desktop.
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
export const toDotNotation = (obj: object, prefix = ''): DotNotationObject => { | |
return Object.entries(obj) | |
.reduce<DotNotationObject>((acc, [key, value]) => { | |
const k = prefix ? `${prefix}.${key}` : key; | |
if (value && typeof value === 'object') { | |
if (Array.isArray(value)) { | |
return value.reduce((arrayAcc, item, index) => { | |
const kA = `${k}[${index}]`; | |
if (item && typeof item === 'object') | |
return { ...arrayAcc, ...toDotNotation(item, kA) }; | |
return { ...arrayAcc, [kA]: item }; | |
}, acc); | |
} | |
return { ...acc, ...toDotNotation(value, k) }; | |
} | |
return { ...acc, [k]: value }; | |
}, {}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment