Skip to content

Instantly share code, notes, and snippets.

@ron4stoppable
Created August 20, 2020 14:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ron4stoppable/185c51266d6b4c0ac924b836bd628091 to your computer and use it in GitHub Desktop.
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
/*
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