Skip to content
Advertisement

Javascript – traversing through object and updating property

I’m hoping someone can point me in the right direction.

I have a JavaScript object like the following …

var category = [{
    isExpanded: false,
    name: "Electricals",
    subcategories: [{
        isExpanded: false,
        name: "Audio",
        subcategories: null
    }, {
        isExpanded: false,
        name: "Photography",
        subcategories: null
    }]
}, {
    isExpanded: false,
    name: "Telecoms",
    subcategories: [{
        isExpanded: false,
        name: "Mobile",
        subcategories: null
    }, {
        isExpanded: false,
        name: "Sim-cards",
        subcategories: null
    }]
}, {
    isExpanded: false,
    name: "Entertainment",
    subcategories: [{
        isExpanded: false,
        name: "Gaming",
        subcategories: [{
            isExpanded: false,
            name: "Games",
            subcategories: null
        }]
    }, {
        isExpanded: false,
        name: "Sports",
        subcategories: null
    }]
}];

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 …

function blah() {
  for (var i = 0; i < category.length; i++) {
    if (category[i].subcategories) {
      console.log(category[i]);
      traverseCategoryTree(category[i]);
    }
  }
}

function traverseCategoryTree(category) {
  //iterate each subcategory and update is Expanded. 
}

blah();

Advertisement

Answer

function traverseCategoryTree(categories) {
  for (var i = 0, len = categories.length; i < len; i++) {
    console.log(categories[i]);
    if (categories[i].subcategories) {
      traverseCategoryTree(categories[i].subcategories);
    }
  }
}    

traverseCategoryTree(category);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement