oakkose
oakkose

Reputation: 405

Vuejs show keys of unknown nested array

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

Upvotes: 0

Views: 112

Answers (1)

Zouhair Lcf
Zouhair Lcf

Reputation: 11

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>

Upvotes: 1

Related Questions