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://timurradkevic.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>
20 changes: 19 additions & 1 deletion src/scripts/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,25 @@ const food = {
const tree = document.querySelector('#tree');

function createTree(element, data) {
// WRITE YOUR CODE HERE
if (Object.keys(data).length === 0) {
return;
}

const ul = document.createElement('ul');
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 <ul> element is created unconditionally. Consider what happens when createTree is called recursively with an empty data object, like for the Wine or Cherry properties. This results in an extra, empty <ul> being added for leaf nodes. A list should only be created if there are items to display in it.


element.appendChild(ul);
Comment on lines +28 to +30
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 <ul> is created and appended even if the data object is empty, which results in an empty list being added to the DOM. A list should only be created if there are items to put inside it. Consider adding a check at the start of the function to handle cases where data has no keys.


for (const key in data) {
const li = document.createElement('li');

li.textContent = key;

if (Object.keys(data[key]).length > 0) {
createTree(li, data[key]);
}

ul.appendChild(li);
}
}

createTree(tree, food);
Loading