使用淘汰赛&foreach'遍历多维数组 [英] Working with Knockout 'foreach' looping through multidimensional array

查看:61
本文介绍了使用淘汰赛&foreach'遍历多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多维关联数组.

I have a multidimensional associative array.

this.items = ko.observableArray([
    { name: "name1", viewable: true, children: [
        { name: "name1-1", viewable: true, children: []},
        { name: "name1-2", viewable: false, children: []}
    ] },
    { name: "name2", viewable: false, children: [] },
    { name: "name3", viewable: true, children: [
        { name: "name3-1", viewable: true, children: []},
    ] },
        { name: "name4", viewable: true, children: [] }
]);

目标是遍历此数组并仅打印出将'viewable'设置为true的值.

The goal is to loop through this array and print out only the values that have 'viewable' set to true.

我使用一堆if和foreach语句来完成这项工作,但是代码开始变得一发不可收拾.此示例仅涉及2个级别,购买我的阵列可以达到 5个级别,因此此代码将成倍增加,并且真正快速.

I have this working using a bunch of if and foreach statements, but the code is starting to get out of hand. This example only covers 2 levels buy my array can get up to 5 levels deep, so this code is going to multiply and get ugly really quick.

<ul data-bind="foreach: items">
    <!-- ko if: viewable -->
    <li data-bind="text: name"></li>
        <!-- ko foreach: children -->
            <!-- ko if: viewable -->
            <li data-bind="text: name"></li>
            <!-- /ko -->
        <!-- /ko -->
    <!-- /ko -->
</ul>

那么有没有更简单/更好的方法来遍历整个数组?

So is there an easier/better way to loop through the entire array?

JS小提琴链接

推荐答案

Underscore.js 有一些不错的方法可以与数组,也许您可​​以使用 flatten 过滤器从您的结构中创建一个数组,然后您只需编写一个 foreach :

Underscore.js has some nice method working with arrays maybe you can use flatten and filter to create one array from your structure then you can just write one foreach:

或者您可以使用模板封装 if:可见逻辑并递归应用模板:

Or you could use templates to encapsulate your if: viewable logic and apply the template recursively:

<script type="text/html" id="template">
  <!-- ko if: viewable -->
    <li data-bind="text: name"></li>    
        <!-- ko template: { name: 'template', foreach: $data.children } -->
        <!-- /ko -->    
  <!-- /ko -->
</script>

<ul data-bind="template: { name: 'template', foreach: items } ">
</ul>

演示 JSFiddle.

这篇关于使用淘汰赛&foreach&amp;#39;遍历多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆