desmondlee
desmondlee

Reputation: 1703

Adding extra object property to knockout mapping

I have a data from server that as follow.

var data = [{
  'Name': 'David',
  'Class': '2A'
}, {
  'Name': 'Vincent',
  'Class': '2B'  
}]

Suppose that i retrieve the data and map it using ko.mapping.fromJS. However, I would like to make the data to consist of another property name Grade after mapping. How can this be achieved? This is because the value of property grade is retrieved through another ajax call, and it should be defined beforehand.

function MyViewModel() {
  var self = this;
  self.StudentProfile = ko.observableArray([]);
  
  self.GetStudentProfile = function() {
    $.ajax({
       ..
       ..
       success: function(data) {
          ko.mapping.fromJS(data.StudentProfile, {}, self.StudentProfile);
          // data after mapping 
          $.each(self.StudentProfile, function (index, value) {
            $.ajax({
                ..
                ..
                success: function(data) {
                   self.StudentProfile()[index].Grade(data);
                }
            });
          }
       }
    })
  }
}

// data after mapping
var data = [{
  'Name': 'David',
  'Class': '2A',
  'Grade': ''
}, {
  'Name': 'Vincent',
  'Class': '2B',
  'Grade': ''
}]

Upvotes: 0

Views: 213

Answers (1)

Dandy
Dandy

Reputation: 2177

You can use

var options = {
    create: function(options){
        options.data.Grade = ko.observable("");
        return options.data;
    }
}

ko.mapping.fromJS(data.StudentProfile, options, self.StudentProfile);

Upvotes: 3

Related Questions