我通过$ http:
获得以下JSON响应{
"fruits": [
{
"name": "apple",
"prices": [
{
"2015": 2
},
{
"2014": 3
},
{
"2013": 5
}
]
},
{
"name": "banana",
"prices": [
{
"2015": 1
},
{
"2014": 3
},
{
"2013": 4
}
]
}
]
}
我正在尝试在Javascript中创建一个地图功能(或多个功能),以便我可以获得以下两组:
$scope.new_data = [
{
name: 'apple',
data: [5,3,2]
},
{
name: 'banana',
data: [4,3,1]
}
]
和
$scope.years = ['2013','2014','2015']
也许是这样的......但我不知道如何将键与值分开:
$scope.new_data = $scope.fruits.map(function(fruit){
return {
name: fruit.name,
data: fruit.prices
};
});
$scope.years = $scope.fruits.map(function(fruit){
return [
fruit.prices.reverse();
];
});
答案 0 :(得分:1)
您可以在一个.map
功能
var formattedData = data.fruits.map(function(fruit) {
return {
name: fruit.name,
data: fruit.prices.map(function(price) {
return price[Object.keys(price)[0]];
}).reverse()
}
});
var years = [];
var allYears = data.fruits.map(function(fruit) {
//Get all years to 2d array
return fruit.prices.map(function(price) {
return Object.keys(price)[0];
});
}).reduce(function(p, c) {
//Flatten 2d array
return p.concat(c)
}, []);
//Remove duplicates
allYears.forEach(function(year) {
if (years.indexOf(year) === -1) {
years.push(year);
}
});