looping through a son array.

44 views
Skip to first unread message

Ricky Spires

unread,
Apr 8, 2016, 9:48:53 AM4/8/16
to KnockoutJS
Hello.

I wonder if anyone couple help me to loop through this json array with knockout js ?

I can get the parent level for options but i cant get the children level.

thanks

this is a sample of the json

{
   
"category": [{
       
"id": 1,
       
"name": "category name",

       
"product": [{
           
"prodId": 1,
           
"name": "product name",

           
"options": [{
               
"optionId": 1,
               
"name": "Colour",
               
"colour": [{
                   
"colourId": 1,
                   
"name": "Black"
               
}, {
                   
"colourId": 2,
                   
"name": "White"
               
}]
           
}]
       
}]
   
}]
}


this is part of the js file



  var self = this;

 
self.products = productData;

 
self.chosenProduct = ko.observable( false );   /* The currently-chosen product object */



this is a loop that gets the top level only


 <div data-bind="foreach: chosenProduct().options">
<ul>
   
<li>
     
<span data-bind="text: name"></span>
   
</li>
</ul>
</div>

that gives the top level of options. i.e

  • Colour
  • Size
  • Addons

but i want to print the children of each option under each parent.



Message has been deleted

noirabys

unread,
Jun 9, 2016, 6:52:20 AM6/9/16
to KnockoutJS
hi ,
if you have different options you may use templates for each option, which are used dynamically.
within the foreach you can refer to the current item with $data or give it a name with 'as' in the binding.


<!DOCTYPE html>
<html>
<head>
  <script src="jquery.js"></script>
<script src="knockout-3.2.0.js"></script>
  <script>
  var productData = {
    "category": [{
        "id": 1,
        "name": "category name",

        "product": [{
            "prodId": 1,
            "name": "product name",

            "options": [{
                "optionId": 1,
                "name": "Colour",
                "colour": [{
                    "colourId": 1,
                    "name": "Black"
                }, {
                    "colourId": 2,
                    "name": "White"
                }]
            }]
        }]
    }]
};
  
  function Model(){
   var self = this;
  var self = this;

  self.products = productData;

  self.chosenProduct = ko.observable( self.products.category[0].product[0]);

      };
  
  $(document).ready(function(){

     model = new Model();
     ko.applyBindings(model);
  });

  </script>
<body>
 <div data-bind="foreach: { data: chosenProduct().options, as:'option'}">
<ul>
   <li>
      <span data-bind="text: option.name"></span>
      <!-- ko foreach: option.colour -->
        <ul>
        <li data-bind="text: name"></li>
        </ul>
      <!-- /ko -->
   </li>
</ul>
</div>  
</body>
</html>
Reply all
Reply to author
Forward
0 new messages