2016-05-14 3 views
0

ich eine json verwende, dies ist die Struktur:AngularJS: doppelte Objekte entfernen und ein Array von Wert neu anordnen

{ "variants": [ 
    { "capacity":"A", "color":"1" }, 
    { "capacity":"A", "color":"2" }, 
    { "capacity":"B", "color":"3" } 
    ]}; 

Mit angular.forEach oder eine andere Methode, würde Ich mag Daten angezeigt werden nicht wiederholt, wird nachbestellt es und bezogen sie von „Kapazität“, so etwas wie dieses (ein neues Array):

$scope.newArray = [ 
    { "capacity":"A", "color1":"1", "color2":"2" }, 
    { "capacity":"B", "color_1":"3" } 
]; 

es ist möglich, eine Winkel Art und Weise oder einfach JavaScript aktivieren, ich brauche Hilfe!

+0

* Entfernen Sie doppelte Werte – nneeggrroo

Antwort

0
a = { 'variants': [ 
     {'capacity': 'A','color': '1'}, 
     {'capacity': 'A','color': '2'}, 
     {'capacity': 'B','color': '3'}, 
]}; 

b = a.variants 
c = b.reduce(function (prev, crt) { 
    prev[crt.capacity] = (prev[crt.capacity] || [ 
    ]).concat(crt.color) 
    return prev; 
}, {}) 
// c is now {"A": ["1","2"], "B": ["3"]} 

d = [] 
for (var name in c) { 
    if (c.hasOwnProperty(name)) { 
    f = { 
     'capacity': name 
    } 
    c[name].forEach(function (e) { 
     f['color' + e] = e; 
    }) 
    // f is {"capacity": "A", "color1": "1","color2": "2"} 
    // and then {"capacity": "B", "color3": "3"} 
    d = d.concat(f) 
    } 
} 

// d is [{"capacity": "A", "color1": "1","color2": "2"}, 
//  {"capacity": "B", "color3": "3"}] 
Verwandte Themen