I am looking to display a nested list with proper indentation based on the level of each object in an array.
Each object is assigned a level, ranging from 0 to 2 where 0 represents the top level and 2 represents the innermost level. The desired output should include indentation to indicate the hierarchy of levels in the list.
An example of the expected list format:
0
1
1
2
2
The current code implementation is as follows:
for (let category of json.categories) {
if ((category.level = 0)) {
console.log(
category.category + "https://www.example.com/" + category.seo_name
);
}
else if ((category.level = 1)) {
console.log(
" " +
category.category +
" " +
"https://www.example.com/" +
category.seo_name
);
}
else if ((category.level = 2)) {
console.log(
" " +
category.category +
" " +
"https://www.example.com/" +
category.seo_name
);
}
}
This code snippet is not only cumbersome but also ineffective as it fails to produce the intended indentation in the output.
Here is an example of the data structure:
const json = {
categories: [
{
category_id: "198",
category: "Appliances",
seo_name: "appliances",
level:0
},
{
category_id: "184",
category: "Industrial Appliances",
seo_name: "industrial-appliances",
level:1
},
],
params: {
visible: false,
sort_order: "asc",
},
};