1

This fiddle shows a list of users being mapped to a function, in that function an observableArray is created surrounding the Roles. For some reason the console log of these mapped users only shows the Roles as and array.

I don't know why?!

var userModel = function (data) {
    var self = this;

    self.FirstName = data.FirstName;
    self.LastName = data.LastName;
    self.Email = data.Email;
    self.ContactTel = data.ContactTel;
    self.ContactMob = data.ContactMob;
    self.Username = data.Username;
    self.Roles = ko.observableArray(data.Roles);
};

Mapping:

self.users = ko.observableArray([]).map(model, userModel);

My observableArray extension:

ko.observableArray.fn.map = function (data, Constructor) {
    var mapped = $.each(data, function (i, e) { return new Constructor(e); });

    this(mapped);

    return this;
};

1 Answer 1

1

You are using $.each when you should be using $.map

ko.observableArray.fn.map = function (data, Constructor) {
    var mapped = $.map(data, function (i, e) { return new Constructor(e); });   
    this(mapped);   
    return this;
};

Also have a look at the mapping plugin. Dont reinvent the wheel

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

2 Comments

I've used each all the time, never had this problem ever.
The return value of the callback used with $.each is only used to break or continue the iterator. $.map is what you want jsfiddle.net/5dXC3/1. Moreover $.each return the orginal object/array sent into $.each for a fluent syntax approuch

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.