Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Tree from object
Write a function `createTree(element, data)` that creates a nested list of `ul/li` from an object.
Use keys as list items.
Write a function `createTree(element, data)` that creates a nested list of `ul/li` from an object.
Use keys as list items.

`element` - is a DOM element

Expand All @@ -11,7 +11,7 @@ Use keys as list items.
![screenshot of the tree](example/object-tree.png)

1. Replace `<your_account>` with your GitHub username in the link
- [DEMO LINK](https://<your_account>.github.io/js_tree-from-object-DOM/)
- [DEMO LINK](https://Rostyslav452.github.io/js_tree-from-object-DOM/)
2. Follow [this instructions](https://github.com/mate-academy/js_task-DOM-guideline)
- Run `npm run test` command to test your code;
- Run `npm run test:only -- -n` to run fast test ignoring linter;
Expand Down
1 change: 1 addition & 0 deletions src/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
/>
</head>
<body>
<div id="tree"></div>
<script src="scripts/main.js"></script>
</body>
</html>
22 changes: 21 additions & 1 deletion src/scripts/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,27 @@ const food = {
const tree = document.querySelector('#tree');

function createTree(element, data) {
// WRITE YOUR CODE HERE
if (Object.keys(data).length === 0) {
return undefined;
Comment on lines +24 to +25
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When data is an empty object {}, this returns undefined without creating or appending the <ul>. For nested empty objects like { Wine: {} }, the li is created but the recursive call returns undefined. While it works in this case, a cleaner approach would be to always create and return the <ul>, letting empty branches simply have an empty <ul>.

}

const ul = document.createElement('ul');

for (const key in data) {
if (Object.entries(data).length === 0) {
continue;
Comment on lines +31 to +32
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This check is redundant. The for...in loop on line 30 will naturally iterate zero times for empty objects, so this condition is never true when the loop executes. The check at line 24 already handles empty objects.

}

const li = document.createElement('li');

li.textContent = key;

createTree(li, data[key]);

ul.append(li);
}

element.append(ul);
}

createTree(tree, food);
Loading