0

我有一个包含类型和名称地址2门阵列等等如下模型:Knockoutjs有关的foreach孩子父母

var model = [{"bstype":1},{"bstype":2},{"bstype":3},{"bstype":4}], 
    [{"bstype":1, "name":"John","Address":"Sample address"}, 
    [{"bstype":1, "name":"John","Address":"Sample address"}, 
    [{"bstype":3, "name":"John","Address":"Sample address"}, 
    {"bstype":2 ,"name":"John","Address":"Sample address"}]; 
    [{"bstype":2, "name":"John","Address":"Sample address"}, 
    [{"bstype":4, "name":"John","Address":"Sample address"}]; 

什么,我想要它做的是创建的列表:

类似于

I am not sure about this part how to implement it that is why it was gibberish. 
    bstype":1 will have a view of following 
    [{"bstype":1, "name":"John","Address":"Sample address"}, 
    [{"bstype":1, "name":"John","Address":"Sample address"}, 
    bstype"2: will have a view of following 
    {"bstype":2 ,"name":"John","Address":"Sample address"}]; 
    [{"bstype":2, "name":"John","Address":"Sample address"}, 
    bstype":3 has only one 
    [{"bstype":3, "name":"John","Address":"Sample address"}, 

等等等等。

我正在使用淘汰赛我检查了网站,它只讨论关于foreach但不知道如何访问子元素。

我希望这是有道理的。

由于

+1

你的例子中的语法没有意义......你已经定义了一个列表,然后是一堆东西。你能解决这个问题吗?这样我们可以更清楚地看到你在做什么? – bdesham 2013-03-06 17:34:50

回答

0

我把他们分开两个变种项第一个包含在所述第一阵列的第二的第二阵列。完成后,我使用第一个数组根据bstype循环4次。然后使用$ .root.secondarray循环遍历第二个项目。 谢谢大家。

1

的helper方法以两个数组组合成你有相同键来完成:

var model = [{"bstype":1},{"bstype":2},{"bstype":3},{"bstype":4}]; 

var modelChildren = [{"bstype":1, "name":"John","Address":"Sample address"}, 
    {"bstype":1, "name":"John","Address":"Sample address"}, 
    {"bstype":3, "name":"John","Address":"Sample address"}, 
    {"bstype":2 ,"name":"John","Address":"Sample address"}, 
    {"bstype":2, "name":"John","Address":"Sample address"}, 
    {"bstype":4, "name":"John","Address":"Sample address"}]; 

这种方法会给你一个新的数组匹配bstype“分组依据”:

var result = model.map(function(elem) 
      { 
       return { 
        bstype: elem.bstype, 
        children: modelChildren.filter(function(childElem) { 
         return childElem.bstype == elem.bstype; 
        }) 
       }; 
      }); 
+0

这是一个好主意,但是我需要什么东西来映射像使用挖空映射插件? – NoviceDeveloper 2013-03-06 20:32:39

+0

您可以直接绑定到由上述方法创建的纯JavaScript对象,但是您是否想要将所有值递归转换为观察对象,以便稍后向其注册更改?如果是这样的话,那么Knockout Mappings插件就会给你所需的东西。在上面的例子中,(ko.mappings.fromJS(result))会给你一个可观察的“结果”版本,它下面的所有东西都会被转化为观察值。 – blaster 2013-03-07 17:25:07

+0

是的,这就是我想要做的。我希望我的模型的元素也是可观察的。 – NoviceDeveloper 2013-03-08 16:45:10

相关问题