Created
June 7, 2022 07:42
-
-
Save iampoul/4613c15ca1bf866140f25f76507ad84a to your computer and use it in GitHub Desktop.
Sort JSON and Create UL LI
This file contains 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
const menuItems = [ | |
{}, | |
{} | |
] | |
const objects = ["fields", "icon"] | |
const fields = [...objects, "title", "slug"] | |
const cleanupJSON = (list: any) => { | |
const json: any = {} | |
const keys = Object.keys(list) | |
for (const key of keys) { | |
if (typeof list[key] === "object") { | |
json[key] = cleanupJSON(list[key]) | |
if (Object.keys(json[key]).length === 0) { | |
delete json[key] | |
} | |
} | |
if (typeof list[key] === "object" && objects.includes(key)) { | |
json[key] = cleanupJSON(list[key]) | |
} | |
else if(fields.includes(key)) { | |
json[key] = list[key] | |
} | |
} | |
return json | |
} | |
const buildListFromJson = (json: any) => { | |
const ul: any[] = [] | |
const keys = Object.keys(json) | |
for (const key of keys) { | |
if (typeof json[key] === "object") { | |
ul.push(buildListFromJson(json[key])) | |
} else { | |
ul.push(`<li>${key}: ${json[key]}</li>`) | |
} | |
} | |
return `<ul>${ul.join("")}</ul>` | |
} | |
const cleanJSON = cleanupJSON(menuItems) | |
const menuList = buildListFromJson(cleanJSON) | |
console.log(cleanJSON) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment