Scoota P
Scoota P

Reputation: 2551

Knockout JS foreach looping through array of objects

I have a observableArray:

self.stats = ko.observableArray([
        {"DFTD" : new Stat("Defensive TD", "DFTD",0,20,0,self.playerGroups[1])},
        {"GL" : new Stat("Games Lost", "GL",0,16,0,self.playerGroups[2])},
        {"FGA" : new Stat("Field Goals ATT", "FGA",0,100,0,self.playerGroups[0])},

    ]);

and i am trying to loop around it with a foreach and then print out the Stat objects name property which is the first element in that object.

<tbody data-bind="foreach: stats" id="stat-sliders">
        <tr>
            <td><span data-bind="text: stats.Stat().name"></span></td>
            <!--/*<td class="statsListItem">
                    </tr>
 </tbody>

Im not sure if im doing it right. I am a beginner with knockout and wondering if anyone can help?

Upvotes: 1

Views: 6720

Answers (2)

John Papa
John Papa

Reputation: 22298

The fiddle below creates an array of football stats, which contains a key field and a stat field. You could use the key field for quicker access if you like. If you want an object where you have the property be the key, that would allow for the quickest indexing, though its not an array then.

See if this is what you want.

http://jsfiddle.net/johnpapa/CgFjJ/

Upvotes: 3

Daniel A. White
Daniel A. White

Reputation: 190943

You shouldn't need to call back into stats. Notice that the span binds to the property of the model that is inside the array.

<tbody data-bind="foreach: stats" id="stat-sliders">
        <tr>
            <td><span data-bind="text: name"></span></td>
            <!--/*<td class="statsListItem">
                    </tr>
 </tbody>

Also, I don't think Knockout works well with keyed arrays like that.

Upvotes: 1

Related Questions