Dukebaby
Dukebaby

Reputation: 204

knockout.js data-bind each array of object

I have json returning:

{
  "school":
     {
       "students":[{"firstName":"John", "lastName":"Doe"},"firstName":"Jane", "lastName":"Doe"}]
     }
}

Then in my markup I have

<ul data-bind="foreach: school.students">
  <li><span data-bind="text: firstName"></span><span data-bind="text: lastName"></span></li>
</ul>

school.students must not be right since it isn't working. Can someone help me with the syntax?

Upvotes: 0

Views: 1130

Answers (2)

Bryan Dellinger
Bryan Dellinger

Reputation: 5304

they have a knockout mapping plugin for this. run snippet below.

var data = {
  "school": {
    "students": [{
      "firstName": "John",
      "lastName": "Doe"
    }, {
      "firstName": "Jane",
      "lastName": "Doe"
    }]
  }
}
var viewModel = ko.mapping.fromJS(data);

$(document).ready(function() {
  ko.applyBindings(viewModel);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.js"></script>

<ul data-bind="foreach: school.students">
  <li><span data-bind="text: firstName"></span><span data-bind="text: lastName"></span></li>
</ul>

http://knockoutjs.com/documentation/plugins-mapping.html

Upvotes: 0

Drummad
Drummad

Reputation: 722

Knockout doesn't work quite like that. You need to build your JSON into some objects before you can use the foreach binding on it.

For example, create a student object with the properties that you need:

function Student(firstName, lastName) {
    this.firstName = ko.observable(firstName);
    this.lastName = ko.observable(lastName);
}

Then when you have your JSON string (maybe in the success callback of your AJAX load) you can create a collection of these student objects from the data:

school.students = ko.utils.arrayMap(json, function(item) {
    return new Student(item.firstName, item.lastName);
});

You can then use the foreach binding as you have done in your small example. Of course I am assuming that you have created a viewmodel and correctly used ko.applyBindings().

Upvotes: 1

Related Questions