Working with Knockout 'foreach' looping through multidimensional array

corabsimcox

New Member
I have a multidimensional associative array.\[code\]this.items = ko.observableArray([ { name: "name1", viewable: true, children: [ { name: "name1-1", viewable: true}, { name: "name1-2", viewable: false} ] }, { name: "name2", viewable: false, children: [] }, { name: "name3", viewable: true, children: [ { name: "name3-1", viewable: true}, ] }, { name: "name4", viewable: true, children: [] }]);\[/code\]The goal is to loop through this array and print out only the values that have 'viewable' set to true.I have this working using a bunch of if and foreach statements, but the code is starting to get out of hand. This example only covers 2 levels buy my array can get up to 5 levels deep, so this code is going to multiply and get ugly really quick.\[code\]<ul data-bind="foreach: items"> <!-- ko if: viewable --> <li data-bind="text: name"></li> <!-- ko foreach: children --> <!-- ko if: viewable --> <li data-bind="text: name"></li> <!-- /ko --> <!-- /ko --> <!-- /ko --></ul>\[/code\]So is there an easier/better way to loop through the entire array?JS Fiddle link
 
Back
Top