Pablo
Pablo

Reputation: 2386

How do I give KO an array inside my JSON data

How do I access the internal array in my JSON data? I'm only showing the first element in the Scores, there are many in the real data. Do I really need to iterate the initialData by hand to get at this internal array?

var initialData = {
    "DateId": 32,
    "Scores": [{
        "Alias": "Joyce",
        "MemberId": 11,
        "Game1": 220
    }...]
};
var theScores = initialData.Scores;
var viewModel = {
    scores: ko.observableArray(theScores)
};

Upvotes: 0

Views: 479

Answers (1)

RP Niemeyer
RP Niemeyer

Reputation: 114792

scores is now an observableArray. To access the underlying array you would need to retrieve the value of the observable like viewModel.scores().

observableArrays do have the majority of the array methods added to them, so you can do things like push or splice directly on the observableArray. This will perform the action and then notify any subscribers that there was a change.

So, basically if you are trying to spit out your array in firebug, then do viewModel.scores(). A handy trick to unwrap all of the observables in a structure is to do ko.toJS(viewModel). This will give you back a plain JavaScript object.

Upvotes: 1

Related Questions