i have an array of objects each of which having the following variables:
class nodeProps {
constructor(id, name, data, parent, children) {
this.id = id;
this.name = name;
this.data = data;
this.parent = parent;
this.children = children;
}
}
each object will become a div tag in the html file with some divs being the child of another. i am having trouble being able to close the tags when they are being nested within each other. what i have so far only adds the first child (i would like to add them all) and doesnt close it:
function createTag(nodes, node) {
if (node.children != null) {
// let kidList = node.children;
let kids = nodes.filter((x) => node.children.includes(x.id));
let tag = `<div className={styles.${node.name}}> ${createTag(
nodes,
kids[0]
)}`;
return tag;
} else {
return `<div className={styles.${node.name}}> </div>\n`;
}
}
i have been ignoring indentation as you currently see it.
CodePudding user response:
Here's an updated version of the function that will correctly create tags for all children and close them properly:
function createTag(nodes, node) {
let tag = `<div className={styles.${node.name}}>`;
if (node.children != null) {
let kids = nodes.filter((x) => node.children.includes(x.id));
for (let i = 0; i < kids.length; i ) {
tag = createTag(nodes, kids[i]);
}
}
tag = `</div>\n`;
return tag;
}
This function uses recursion to create tags for all children and their children, and appends them to the parent tag. The parent tag is then closed at the end.