0

I hava a sample and dynamic array like this:

 nodes: [
 {
 n1: "Foods",
 },
 {
 n4: "Drinks",
 b7: [
 {
 a2: "Beers",
 a4: [
 {
 a5: "Budweiser",
 a6: "deneme",
 },
 {
 a7: "Heineken",
 },
 {
 a8: "1",
 a9: "2",
 
 },
 
 ],
 },
 {
 z1: "Wines",
 },
 {
 z2: "Whiskey",
 },
 ],
 },
 ]

This array always changes dynimacally. I want to show this array keys in a tree table. So we should see relationship between parens and child. For example:

n1
n4
 b7
 a2
 a4
 a5
 a6
asked Dec 23, 2021 at 20:49

1 Answer 1

1

I have created this using vanilla javascript :

(async () => {
 var nodes = [{"n1":"Foods"},{"n4":"Drinks","b7":[{"a2":"Beers","a4":[{"a5":"Budweiser","a6":"deneme"},{"a7":"Heineken"},{"a8":"1","a9":"2"}]},{"z1":"Wines"},{"z2":"Whiskey"}]}];
 var tree = "";
 // Map each Node from the nodes
 async function mapNodes(nodes) {
 nodes.map(async (node) => {
 await mapNode(node);
 });
 }
 // Map each key from the Node
 async function mapNode(node) {
 tree += `<ul>`;
 Object.keys(node).map((key) => {
 mapKeys(node[key], key);
 });
 tree += `</ul>`;
 }
 // handle each key value
 async function mapKeys(elm) {
 if (typeof elm === "string") {
 tree += `<li>${elm}</li>`;
 } else if (typeof elm === "object") {
 await mapNode(elm);
 } else if (Array.isArray(elm)) {
 await mapNodes(elm);
 }
 }
 // start of the loop
 await mapNodes(nodes);
 // you can see the tree by injecting ${tree} variable to the DOM
 document.querySelector("div").innerHTML = tree;
})();
<div></div>

TAHER El Mehdi
9,5947 gold badges32 silver badges51 bronze badges
answered Dec 23, 2021 at 22:56
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.