0

I am trying to perform conversion of property to observable with the use of komapping plugin.

I do have array of same kind of objects like below:

 var data =[{ b1: "v1", b2: "b21" }, { b1: "v2", b2: "b22" }] ;

Now I wanted to property b1 as if and b2 to be converted to observable with the use of komapping. For simplicity I have kept here only two properties but in realty I do have more properties.

so I tried it like following:

var data = [{ b1: "v1", b2: "b21" }, { b1: "v2", b2: "b22" }] ;
var result = ko.mapping.fromJS(data, { copy: "b1" });
console.log(result());

But it does not work here is the jsfiddle

enter image description here

Jenish Rabadiya
  • 6,708
  • 6
  • 33
  • 62

1 Answers1

1

I think your current mapping options only check for a b1 property name in the first data you pass, i.e.: the data array.

One way to fix this (maybe not the easiest, I'm not sure), is to define how to process each item:

var data = [{ b1: "v1" }, { b1: "v2" }];

var result = ko.mapping.fromJS(data, {
    create: function(options) {
      var nestedData = options.data;
      return ko.mapping.fromJS(nestedData, { 'copy': 'b1' });
    }
});

Each item in data is passed to the create method inside options.data (the original data remains accessible through either data or options.parent).

The create function returns a mapped object using the mapping you originally tried.

Here's an updated fiddle: http://jsfiddle.net/1ftk3a03/

user3297291
  • 22,592
  • 4
  • 29
  • 45