在angularjs中的对象内添加对象数组

在angularjs中的对象内添加对象数组,angularjs,Angularjs,我想存储一个带有名称的类别列表,在每个类别名称下,我想添加带有名称和价格的项目 我该怎么做 var item = { categoryName : "", budgetItemList : [{ itemName : "", price : 0 }] }; if (!$scope.budgetObj.categoryList) { $scope.budgetObj.cat

我想存储一个带有
名称的类别列表
,在每个类别名称下,我想添加带有名称和价格的项目

我该怎么做

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

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

这里有一种存储类别列表的方法,每个类别都有一个项目和价格列表

$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);

您可以使用类似哈希映射的方法:

$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);
        }
    }
}