2

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]

2 Answers 2

6

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

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

1 Comment

doh!! Tnx a lot mate! I was very tired and I missed create
2

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.

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.