淘汰foreach数字数组

时间:2015-03-24 23:15:34

标签: javascript knockout.js durandal

我有这个数组:

[{"room_id":"1","room_name":"CDI","workers":[[{"worker_id":"12","worker_name":"FF","worker_grade":"Q2"},{"worker_id":"13","worker_name":"Test","worker_grade":"Q1"}],[{"worker_id":"12","worker_name":"FF","worker_grade":"Q2"},{"worker_id":"13","worker_name":"Test","worker_grade":"Q1"}],[],[],[{"worker_id":"13","worker_name":"Test","worker_grade":"Q1"}]]},{"room_id":"2","room_name":"DD","workers":[[],[],[],[{"worker_id":"12","worker_name":"FF","worker_grade":"Q2"},{"worker_id":"13","worker_name":"Test","worker_grade":"Q1"}],[]]}]

我的问题是y viewmodel中的循环:

 <tbody data-bind="foreach: rooms">
            <tr>
                <th data-bind="text: room_name"></th>
                <!--ko foreach: workers-->
                <td>
                <!--ko foreach: 0-->
                <!--ko text: worker_name--><!--/ko-->
                    <!--/ko-->
                </td>
                <td>
                    <!--ko foreach: 1-->
                    <!--ko text: worker_name--><!--/ko-->
                    <!--/ko-->
                </td>
                <td>
                    <!--ko foreach: 2-->
                    <!--ko text: worker_name--><!--/ko-->
                    <!--/ko-->
                </td>
                <td>
                    <!--ko foreach: 3-->
                    <!--ko text: worker_name--><!--/ko-->
                    <!--/ko-->
                </td>
                <td>
                    <!--ko foreach: 4-->
                    <!--ko text: worker_name--><!--/ko-->
                    <!--/ko-->
                </td>
                <!--/ko-->
            </tr>
        </tbody>

因为工人之后的数组不是关联的,所以我不能循环使用它。但是我现在怎样才能完成它并显示其他数组:

[{"worker_id":"12","worker_name":"Adriaan Wind","worker_grade":"Q2"},{"worker_id":"13","worker_name":"Test","worker_grade":"Q1"}]

上述解决方案不起作用。

1 个答案:

答案 0 :(得分:0)

我认为您需要为房间绑定添加类似“房间”的名称,并为工作人员相关绑定添加“工作人员”。然后您可以按照以下方式绑定您的详细信息

 ko.applyBindings(
     { "rooms" : [{ "room_id":"1","room_name":"CDI",
       "workers":[{"worker_id":"12",                                                                          "worker_name":"FF",
                    "worker_grade":"Q2"},
                  {"worker_id":"13", 
                   "worker_name":"Test",
                   "worker_grade":"Q1"}
                 ]}
                 ]});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.0.0/knockout-min.js"></script>
<div data-bind="foreach: rooms">
    Room <span data-bind="text:room_name "></span>
    <div data-bind="foreach: workers">
        Worker: <span data-bind="text: worker_name"></span><hr/>
    </div>
</div>