Last active
November 24, 2020 20:09
-
-
Save chiro-hiro/9fef68439475bc5ab6646be9c9452143 to your computer and use it in GitHub Desktop.
Transform nested object to keys-values
This file contains hidden or 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
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