Vuejs显示未知嵌套数组的键



我有一个像这样的示例和动态数组:

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

},

],
},
{
z1: "Wines",
},
{
z2: "Whiskey",
},
],
},
]

这个数组总是动态变化。我想在树表中显示这个数组键。所以我们应该看到父母和孩子之间的关系。例如:

n1
n4
b7
a2
a4
a5
a6

我使用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>

最新更新