Michael Lee
Michael Lee

Reputation: 135

AngularJS and JSON Array

I am trying to arrange the existed JSON Array following as below by using AngularJS filter such as $filter, but it is failing.

 {
        {       
            name: "name 1",         
            label: "A",     
        },
        {       
            name: "name 2",         
            label: "A",     
        },
        {       
            name: "name 3",         
            label: "B",     
        },
        {       
            name: "name 4",         
            label: "B",     
        },
        {       
            name: "name 5",         
            label: "B",     
        },
        {       
            name: "name 6",         
            label: "C",     
        },
        {       
            name: "name 7",         
            label: "C",     
        },
        {       
            name: "name 8",         
            label: "C",     
        },
        {       
            name: "name 9",         
            label: "D",     
        }
    }

What I want is to arrange this array to new one following as below.

{
    "A" : { 
        {       
            name: "name 1",         
            label: "A",     
        },
        {       
            name: "name 2",         
            label: "A",     
        },
    },
    "B" : {
        {       
            name: "name 3",         
            label: "B",     
        },
        {       
            name: "name 4",         
            label: "B",     
        },
        {       
            name: "name 5",         
            label: "B",     
        },
    },
    "C" : {
        {       
            name: "name 6",         
            label: "C",     
        },
        {       
            name: "name 7",         
            label: "C",     
        },
        {       
            name: "name 8",         
            label: "C",     
        },
    },
    "D" : {
        {       
            name: "name 9",         
            label: "D",
        }
    }   
}

How can I get the new array using angularJS?

Upvotes: 1

Views: 67

Answers (2)

shershen
shershen

Reputation: 9993

If you were using lodash, you could utilise _.groupBy function for this:

var grouppedArray = _.groupBy(myArray, function(i){
  return i.label;
})

To extract only labels you could smth like this

var uniqueLables = [];
angular.forEach(myArray, function(obj){
  if(uniqueLables.indexOf(obj.label) == -1) uniqueLables.push(obj.label)
})

Upvotes: 2

aseferov
aseferov

Reputation: 6393

try this

   var result = {}
   angular.forEach(jsonData, function(obj){
       if(!result.hasOwnProperty(obj.label) result[obj.label] = []
       result[obj.label].push(obj)
   })

   console.log(result)

Upvotes: 0

Related Questions