Oden
Oden

Reputation: 754

knockoutjs mapping custom objects with nesting array

i want to map this json to custom objects. The problem is that items are not typeof Item object but normal Objects. What I'm missing here?

You can test here: http://jsfiddle.net/5jhpE/

var json = [
    {
        id: 1,
        items: [
            {id: 1, name: 'item1'},
            {id: 2, name: 'item2'},
            {id: 3, name: 'item3'}
        ]
    },
    {
        id: 2,
        items: [
            {id: 4, name: 'item4'},
            {id: 5, name: 'item5'},
            {id: 6, name: 'item6'}
        ]
    },
]

function Data(data) {
    ko.mapping.fromJS(data, {}, this);
}

function Item(data) {
    ko.mapping.fromJS(data, {}, this);
}
var map = {
    create: function(options) {
        return new Data(options.data);
    },
    items: function(options) {
        return new Item(options.data);
    },
}

var res = ko.mapping.fromJS(json, map);

Output:

console.log(res());
[Data, Data]
--
console.log(res()[0].items());
[Object, Object, Object] <-- Here I want to have [Item, Item, Item]

Upvotes: 2

Views: 5067

Answers (2)

Francesco Pez
Francesco Pez

Reputation: 676

I've changed your mapper options in this way

var map = {
    'items': {
        create: function(options) {
            return new Item(options.data);
        }
    }
}

and seems fine; Could you try?

If you need: jsfiddle the console output is [Item, Item, Item] as you want;


I permit to add one little suggestion: if you need to test the typeof in this way:

typeof res()[0].items()[0]

pay attention, it could be tricky!

To avoid any problem, I usually declare the Item viewModel in this way:

function Item(data) {
    var self = this;
    self.myType = 'item';
    ko.mapping.fromJS(data, {}, this);
}

so you can simply test, for example :

if('item' === res()[0].items()[0].myType) {
  //do something...
}

This "myType" trick was suggests here in stackoverflow some time ago: I'll post the link here as soon I'll find the post

Upvotes: 6

KodeKreachor
KodeKreachor

Reputation: 8882

Take a look at this question: Map JSON data to Knockout observableArray with specific view model type

It maps custom nested objects and also contains a fiddle that does so.

Upvotes: 2

Related Questions