0

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?

2
  • not sure how to update the question since my li was lost... but basically I have data-bind"foreach: school.students" Commented May 25, 2017 at 13:06
  • Are you using the mapping plugin? We need to see the full context here of how you're creating your view model and any bindings of parent HTML elements. Commented May 25, 2017 at 13:12

2 Answers 2

1

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().

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.