2013-04-06 93 views
-1

在段對象中,我有一個CategoryId - 就像一個外鍵。 現在,我想將每個部分複製到匹配的類別對象中。擴展一個對象(嵌套)

來源:

var sections = [{title:"FirstSection", CategoryId : 1}, 
       {title:"SecondSection", CategoryId : 1}, 
       {title:"ThirdSection", CategoryId : 2}]; 
var categories = [{title:"Cat1", Id : 1}, 
       {title:"Cat2", Id : 2}]; 

結果是這樣的:

categories = [{title:"Cat1", 
       Id : 1, 
       sections : [{title:"FirstSection", CategoryId : 1}, 
          {title:"SecondSection", CategoryId : 1}] 
       }, 
       {title:"Cat2", 
       Id : 1, 
       sections: [{title:"ThirdSection", CategoryId : 2}] 
       }]; 

CategoryId = 1所有部分現在是在使用id = 1

也許類別的部分陣列我正在尋找錯誤的關鍵字,但我找不到解決方案。

+0

這兩個簡單的實現了循環做了什麼你確切的問題是? – 2013-04-06 20:31:58

+1

這些都是對象的數組,你的代碼中沒有任何與JSON有關的東西。 – 2013-04-06 20:47:04

回答

1

如果supported(> IE8和所有其他瀏覽器),這是很容易與...

categories.forEach(function(category) { 
    category["sections"] = sections.filter(function(s) { 
     return s.CategoryId === category.Id; 
    }); 
}); 

Example

1

在這種情況下,我會使用下劃線庫(你可以手工完成)。

http://underscorejs.org/#findWhere

如您遍歷所有的類別陣列,您可以輕鬆地做這樣的事情:

_.findWhere(sections, {categoryId: 1}); 

而且與下劃線你可以:

var combined = _.groupBy(categories, function(cat){ 
    cat.sections = _.findWhere(sections, {CategoryId: cat.Id}); 
    return cat; 
}); 

並結合會有什麼你正在找。

演示:http://jsfiddle.net/lucuma/kjkkV/1/

+0

我喜歡那種功能性的方法。我在下劃線庫中搜索這種函數。謝謝! – 2013-04-06 20:42:31

+0

下劃線庫非常棒。 – lucuma 2013-04-06 20:43:41