Skip to content

Instantly share code, notes, and snippets.

@RodrigoNovais
Created July 27, 2024 02:10
Show Gist options
  • Save RodrigoNovais/8c2b9d7c2003af93d9b7f9cd7ba8ceeb to your computer and use it in GitHub Desktop.
Save RodrigoNovais/8c2b9d7c2003af93d9b7f9cd7ba8ceeb to your computer and use it in GitHub Desktop.
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