Created
August 20, 2020 14:54
-
-
Save ron4stoppable/185c51266d6b4c0ac924b836bd628091 to your computer and use it in GitHub Desktop.
Deep JSON object to flat JSON object preserving the nested structure with a delimiter
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
/* | |
Deep JSON object to flat JSON object preserving the nested structure with a delimiter. | |
Can use for dynamic forms | |
*/ | |
function jsonToSSFlatmap (obj: any, prefix: string) { | |
let list: any = {}; | |
for (const key in obj) { | |
if (obj.hasOwnProperty(key)) { | |
const element = obj[key]; | |
if (typeof element === "object") { | |
const li = jsonToSSFlatmap( element, (prefix ? prefix + "||" : "") + key); | |
list = { | |
...list, | |
...li | |
}; | |
} else { | |
list[(prefix ? prefix + "||" : "") + key] = element; | |
} | |
} | |
} | |
return list; | |
}; | |
function ssFlatmapToJSON(values: {[key:string]: string}) { | |
const payload: { | |
[key: string]: string | number | any; | |
} = {}; | |
for (const driverKey in values) { | |
// __ - private keys, can use for any other special case | |
if (!driverKey.startsWith("__") && driverKey.includes("||")) { | |
const propNames = driverKey.split("||"); | |
const lastKey = propNames.pop() as string; | |
let prop: any = payload; | |
propNames.forEach((propName) => { | |
if (!prop.hasOwnProperty(propName)) { | |
prop[propName] = {}; | |
} | |
prop = prop[propName]; | |
}); | |
prop[lastKey] = values[driverKey]; | |
} else if (values.hasOwnProperty(driverKey)) { | |
payload[driverKey] = values[driverKey]; | |
} | |
} | |
return payload; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment