Mohsin JK
Mohsin JK

Reputation: 571

Mapping JSON into Knockout Observable Array

1st web service: (User)

[{id:1, UserName:"Jhon"}]

2nd web service: (Message)

[{id:34, Message:"This is a message 1", UserId:1}, {id:35, Message:"This is a message 2", UserId:1}]

How I can map above two ko.obervableArrays so that I can get UserName("Jhon") in my Message ViewModel on base of UserId.

As you know UserId:1 is foreign key of User.

I want to user Message and UserName something like this.

Upvotes: 0

Views: 342

Answers (2)

mhu
mhu

Reputation: 18061

You could use the create option of the mapping plugin to include the user data, like this: http://jsfiddle.net/H4QfX/

var userData = [{id:1, UserName:"Jhon"}],
    messageData = [{id:34, Message:"This is a message 1", UserId:1}, {id:35, Message:"This is a message 2", UserId:1}];

var users = ko.mapping.fromJS(userData);
var viewModel = ko.mapping.fromJS(messageData, {
    'UserId': {
        create: function(options) {
            return ko.utils.arrayFirst(users(), function(u) {
                if (u.id() == options.data) {
                    return u;
                }
            });
        }
    }});

ko.applyBindings(viewModel);

Upvotes: 1

PW Kad
PW Kad

Reputation: 14995

If you used a javascript library like Breeze your life would be much simplified. Without Breeze, you will need to create the model classes in the JavaScript much like you have in your model classes for EF. Basically you will need to maintain a back-end model definition as well as a front-end model definition, and make sure they match.

I would highly recommend looking at breezejs.com as I cannot stress enough how much easier this will make your life. Breeze can inherit your metadata from your EF datacontext and map everything properly from the start, it works hand in hand with knockout, and it will save you weeks of development.

If you want you can also use the Knockout mapping plugin Using Knockout mapping for complex JSON

Upvotes: 2

Related Questions