Skip to content

Instantly share code, notes, and snippets.

@chiro-hiro
Last active November 24, 2020 20:09
Show Gist options
  • Save chiro-hiro/9fef68439475bc5ab6646be9c9452143 to your computer and use it in GitHub Desktop.
Save chiro-hiro/9fef68439475bc5ab6646be9c9452143 to your computer and use it in GitHub Desktop.
Transform nested object to keys-values
function objectToMap(obj: any, key: string[] = [], mapResult?: Map<string, any>) {
if (typeof mapResult === 'undefined') {
mapResult = new Map<string, any>();
}
if (typeof obj === 'object' && obj !== null && !Array.isArray(obj)) {
const k = Object.keys(obj);
for (let i = 0; i < k.length; i += 1) {
if (typeof obj[k[i]] !== 'object') {
mapResult.set(key.concat([k[i]]).join('.'), obj[k[i]]);
} else if (obj[k[i]] !== null) {
key.push(k[i]);
objectToMap(obj[k[i]], [...key], mapResult);
key.pop();
}
}
}
return mapResult;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment