[英]Can I put an object and an array together inside another array?
我有兩個要組合在一起的對象,然后將它們都放置在數組中。
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都放置在所選對象中時,似乎出現錯誤。
我想要這樣的輸出:[{name,picture},{name,picture},{name,picture}]
您不能創建沒有名稱的對象屬性:
//object with properties 'name' & 'picture'
var selected = {
name: vm.data.name,
picture: vm.data.picture
}
或者如果確實需要僅使用數據(糟糕的方式),則可以使用數組:
var selected = [
vm.data.name,
vm.data.picture
]
JavaScript對象是鍵值對。 構造對象時缺少鍵
var selected = {
name: vm.data.name,
picture: vm.data.picture
} // Where I group the two.
您可以直接推動而不用selected
vm.category_name_image.push({
name: vm.data.name,
picture: vm.data.picture
});
您的示例中有錯字。
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.
// 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});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.