I’m hoping someone can point me in the right direction.
I have a JavaScript object like the following …
JavaScript
x
42
42
1
var category = [{
2
isExpanded: false,
3
name: "Electricals",
4
subcategories: [{
5
isExpanded: false,
6
name: "Audio",
7
subcategories: null
8
}, {
9
isExpanded: false,
10
name: "Photography",
11
subcategories: null
12
}]
13
}, {
14
isExpanded: false,
15
name: "Telecoms",
16
subcategories: [{
17
isExpanded: false,
18
name: "Mobile",
19
subcategories: null
20
}, {
21
isExpanded: false,
22
name: "Sim-cards",
23
subcategories: null
24
}]
25
}, {
26
isExpanded: false,
27
name: "Entertainment",
28
subcategories: [{
29
isExpanded: false,
30
name: "Gaming",
31
subcategories: [{
32
isExpanded: false,
33
name: "Games",
34
subcategories: null
35
}]
36
}, {
37
isExpanded: false,
38
name: "Sports",
39
subcategories: null
40
}]
41
}];
42
My goal is to iterate through each category/subcategory and set the value of ‘isExpandable’ depending on my logic. Can some advise how I can iterate through through each subcategory of the object, baring in mind that a subcategory and also have a subcategory and so on?
Here is my current attempt …
JavaScript
1
15
15
1
function blah() {
2
for (var i = 0; i < category.length; i++) {
3
if (category[i].subcategories) {
4
console.log(category[i]);
5
traverseCategoryTree(category[i]);
6
}
7
}
8
}
9
10
function traverseCategoryTree(category) {
11
//iterate each subcategory and update is Expanded.
12
}
13
14
blah();
15
Advertisement
Answer
JavaScript
1
11
11
1
function traverseCategoryTree(categories) {
2
for (var i = 0, len = categories.length; i < len; i++) {
3
console.log(categories[i]);
4
if (categories[i].subcategories) {
5
traverseCategoryTree(categories[i].subcategories);
6
}
7
}
8
}
9
10
traverseCategoryTree(category);
11