与淘汰赛“的foreach”通过多维数组循环工作 [英] Working with Knockout 'foreach' looping through multidimensional array

查看:119
本文介绍了与淘汰赛“的foreach”通过多维数组循环工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多维数组。

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: [] }
]);

我们的目标是要遍历这个数组并打印出只有那些可见设置为true值。

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

我用了一堆,如果和foreach语句这个工作,但code开始变得不可收拾。这个例子只包括2级买我的阵列可以得到高达 5级深,所以这个code会繁殖并变得丑陋的真快

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 有一些不错的方法一起工作阵列也许你可以使用扁平化并的过滤,向你的结构创建一个数组,那么你可以只写一个的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:

或者你可以使用模板来封装你的,如果:可视逻辑和应用递归模板:

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”通过多维数组循环工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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