Join the Stack Overflow Community
Stack Overflow is a community of 6.6 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

create a json array structure with key using angularjs. I don't have any idea to how to push data to create json array structure with key. I want to json array using below json data.

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

        }
    }
}

I want output like this:

  {
    "vegetable" : [
        { "id" : 1, "name" : "tomato"},
        { "id" : 2, "name" : "potato"},
        { "id" : 3, "name" : "onion"},
    ],
    "fruits" : [
        { "id" : 3, "name" : "orange"},
        { "id" : 4, "name" : "apple"}
    ]
 }
share|improve this question
up vote 3 down vote accepted

To get your desired format you need to categoryId from json before injecting it.

Code

$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;
}
share|improve this answer
    
or if you just want id and name form data use this array.push({ id: $scope.data[j].id, name: $scope.data[j].name }); – JAG May 5 '15 at 18:36
    
@JAG Take a look at my solution – Pankaj Parkar May 5 '15 at 18:40
    
yeah.. that works too.. – JAG May 5 '15 at 18:41
    
@JAG glad to help you. Thanks :) – Pankaj Parkar May 5 '15 at 18:43

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.