2017-02-16 44 views
0

我想存儲類別列表names,並且在每個類別名稱下,我想添加具有其名稱和價格的項目。在angularjs中的對象內添加對象數組

我該怎麼做?

var item = { 
    categoryName : "", 
    budgetItemList : [{ 
     itemName : "", 
     price : 0 
    }]        
}; 

if (!$scope.budgetObj.categoryList) { 
    $scope.budgetObj.categoryList = []; 
} 
$scope.budgetObj.categoryList.push(item); 

回答

0

這裏有一種方法來存儲類別列表,每個類別都有一個項目和價格列表。

$scope.categories = [ 
    { 
     categoryName: "Books", 
     items: [ 
      { 
       itemName: "Harry Potter", 
       price: 52.16 

      }, 
      { 
       itemName: "LOTR", 
       price: 21.46 
      } 
     ] 

    }, 
    { 
     categoryName: "Laptops", 
     items: [ 
      { 
       itemName: "MacBook Pro", 
       price: 1200 

      } 
     ] 
    }, 
    { 
     categoryName: "Mobiles" 
    } 
]; 
var item = { 
    itemName: "iPhone7", 
    price: 600 
} 

if (!$scope.categories[2].items) $scope.categories[2].items = []; 
$scope.categories[2].items.push(item); 
0

你可以使用一個哈希地圖樣的方法:

$scope.categories = {}; 
// assuming you have an array with all the category names 
for(categoryName in categoryNames){ 
    $scope.categories[categoryName] = []; 
    // assuming you have an array with all the items 
    for(item in items){ 
     if(item.categoryName === categoryName) { 
      var newItem = {price: item.price, name: item.name}; 
      $scope.categories[categoryName].push(newItem); 
     } 
    } 
}