简体   繁体   中英

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?

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/

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM