Michael Lee Michael Lee - 6 months ago 8
Javascript Question

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?

Answer

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