Skip to content

Instantly share code, notes, and snippets.

@iampoul
Created June 7, 2022 07:42
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 iampoul/4613c15ca1bf866140f25f76507ad84a to your computer and use it in GitHub Desktop.
Save iampoul/4613c15ca1bf866140f25f76507ad84a to your computer and use it in GitHub Desktop.
Sort JSON and Create UL LI
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