简体   繁体   中英

looping through Javascript array and displaying HTML (knockout)

I want to display JSON data which is my model. This is an example of what could be in it:

{"id":"1","name":"1","category":"A" },
{"id":"2","name":"2","category":"B" },
{"id":"3","name":"3","category":"A" },
{"id":"4","name":"4","category":"B" }

What I want is distinct al categories with javascript into an array i guess: A B.

And then foreach element in array matching cat A print it like so with knockout:

<div data-bind="template: { name: template, foreach: LISTOFITEMS }"></div>

<script id="template">
<h1 data-bind="text: Category></h1>
<div data-bind=" foreach: LISTOFITEMSmatchingcategory ">
<li data-bind="text: name"></li>
</div> 
</script>

Is this the way to go? I want to make stuff easily sortable (the array is an observable array)

Try the following way: -

 var self = this; self.listArr = ko.observableArray([ {"id":"1","name":"1","category":"A" }, {"id":"2","name":"2","category":"B" }, {"id":"3","name":"3","category":"A" }, {"id":"4","name":"4","category":"B" } ]); self.listA = ko.observableArray([]); self.listB = ko.observableArray([]); for(var i in self.listArr()) { if(self.listArr()[i].category == "A") { self.listA.push(self.listArr()[i]); } else if(self.listArr()[i].category == "B") { self.listB.push(self.listArr()[i]); } } ko.applyBindings(self); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script> <div>List A</div> <div data-bind="foreach:listA"> <span data-bind= "text : $data.name"></span> <br/> </div> <div>List B</div> <div data-bind="foreach:listB"> <span data-bind= "text : $data.name"></span> <br/> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM