2015-08-17 61 views
1

我有兩個對象,我想組合在一個對象中,然後將它們放在一個數組中。我可以將一個對象和一個數組放在另一個數組中嗎?

vm.data = {}; 
vm.category_name_image = [] ; 

getProductFunc=function(){ 

     $http.get(ConfigCnst.apiUrl+'?route=categories').success(function (res) { 
      //console.log(res); 
      var sub_category = res; 
      console.log(sub_category); 
      var bagmankey = '-JweP7imFLfnh96iwn-c'; 
      //console.log(bagmankey); 
      angular.forEach(sub_category, function (value, key) { 
       if (value.parentKey == bagmankey) { 
       // where i loop   
        vm.data.name = value.name; 
        vm.data.picture = value.image; 

        var selected = { 
          vm.data.name, 
          vm.data.picture 
         } // Where I group the two. 

         vm.category_name_image.push(seleted); 
         // where i want to place the both. 


       } 

      }); 


      }); 
    } 

當我將vm.data.name和vm.data.picture放在所選對象中時,我似乎會收到錯誤。

我想我的輸出是這樣的:[{名稱,圖片},{名稱,圖片},{名稱,圖片}]

+0

「_I似乎得到一個錯誤_」 你應該告訴我們是什麼錯誤。此外,這看起來像JavaScript,但被標記爲Java。你應該解決這個問題。 – csmckelvey

+0

如何創建一個對象模型,然後創建一個基於模型的數組? –

+0

@Takendarkk,我的控制器不確定... – Pickles

回答

3

你不能沒有名字創建對象屬性:

//object with properties 'name' & 'picture' 
var selected = { 
    name: vm.data.name, 
    picture: vm.data.picture 
} 

或者您可以使用數組,如果你真的需要使用唯一的數據(壞的方式):

var selected = [ 
    vm.data.name, 
    vm.data.picture 
] 
+0

你需要解釋每一個是什麼。 – SLaks

+0

@ user3335966我明白了,看起來我的錯誤是語法,我沒有用vm.data.name添加「name:」。 – Pickles

1

JavaScript對象是關鍵值對。這是因爲丟失了鑰匙,當你構造對象

​​

您可以通過該方式直接推不使用selected

vm.category_name_image.push({ 
    name: vm.data.name, 
    picture: vm.data.picture 
}); 
1

您的例子一個錯字。

var selected = { 
    vm.data.name, 
    vm.data.picture 
}; // Where I group the two. 

vm.category_name_image.push(seleted); 
// where i want to place the both. 

應該

//it would be better to assign name and picture to properties of the object 
var selected = { 
    name: vm.data.name, 
    picture: vm.data.picture 
}; // Where I group the two. 

//you had a typo here --- it should be selected not seleted 
vm.category_name_image.push(selected); 
// where i want to place the both. 
1
// where i loop   
vm.data.name = value.name; 
vm.data.picture = value.image; 
var selected = { 
    vm.data.name, 
    vm.data.picture 
} // Where I group the two. 

vm.category_name_image.push(seleted); 
// where i want to place the both. 
} 

您可以使用下面的代碼,而不是

vm.category_name_image.push({name:value.name, picture:value.image}); 
相關問題