我使用的是json,这是结构:
{ "variants": [
{ "capacity":"A", "color":"1" },
{ "capacity":"A", "color":"2" },
{ "capacity":"B", "color":"3" }
]};
使用angular.forEach
或其他方法,我想显示没有重复的数据,重新排序并通过“容量”将其关联,就像这样(一个新数组):
$scope.newArray = [
{ "capacity":"A", "color1":"1", "color2":"2" },
{ "capacity":"B", "color_1":"3" }
];
这可能是一种有角度的方式或简单的javascript,我需要帮助!
答案 0 :(得分: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"}]