关于foreach孩子父母的Knockoutjs

时间:2013-03-06 17:30:29

标签: knockout.js knockout-mapping-plugin knockout-2.0 knockout-mvc knockout-sortable

我的模型包含2个类型和名称地址的数组,依此类推如下:

  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而不是如何访问子元素。

我希望这是有道理的。

由于

2 个答案:

答案 0 :(得分:1)

使用相同的键完成两个数组组合的辅助方法:

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;
                  })
              };
          });

答案 1 :(得分:0)

我将它们分成两个var项,第一个包含第一个数组,第二个数组包含第二个数组。完成后,我使用第一个数组基于bstype循环4次。然后使用$ .root.secondarray循环遍历第二个项目。 谢谢大家。