2015-05-05 39 views
1

使用angularjs创建json数组结构,使用key。我不知道如何推动数据创建与key json数组结构。我想使用下面的json数据json数组。使用AngularJS创建带有密钥的JSON数组

$scope.category = [{"id": 20, "name": "vegetable"}, 
    {"id": 30, "name": "fruits"}]; 

$scope.data = [ 
    { "id" : 1,"name" : "tomato", "categoryId" : 20}, 
    { "id" : 2,"name" : "potato", "categoryId" : 20}, 
    { "id" : 3,"name" : "orange", "categoryId" : 30}, 
    { "id" : 4,"name" : "apple", "categoryId" : 30}, 
    { "id" : 4,"name" : "onion", "categoryId" : 20}]; 

for(var i=0; i<$scope.category.length; i++) { 
    for(var j=0; j<$scope.data.length; j++) { 
     if($scope.category[i].id === $scope.data[j].categoryId) { 

     } 
    } 
} 

我想输出是这样的:

{ 
    "vegetable" : [ 
     { "id" : 1, "name" : "tomato"}, 
     { "id" : 2, "name" : "potato"}, 
     { "id" : 3, "name" : "onion"}, 
    ], 
    "fruits" : [ 
     { "id" : 3, "name" : "orange"}, 
     { "id" : 4, "name" : "apple"} 
    ] 
} 

回答

4

为了让您注射前一定JSON需要categoryId你想要的格式。

代码

$scope.myArray = []; 
for(var i=0; i<$scope.category.length; i++) { 
    var array = []; 
    for(var j=0; j<$scope.data.length; j++) { 
     if($scope.category[i].id === $scope.data[j].categoryId) { 
      var index = array.push($scope.data[j]); 
      delete array[index-1].categoryId; 
     } 
    } 
    $scope.myArray[$scope.category[i].name] = array; 
} 
+0

或者如果你只是想'id'和'name'形式'data'使用'的Array.push({ID:$ scope.data [J] .ID,名称:$ scope.data [j] .name});' – Jag

+0

@JAG看看我的解决方案 –

+0

是的.. ..太有用了.. – Jag

相关问题