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