Reputation: 863
I have the following JSON response via $http:
{
"fruits": [
{
"name": "apple",
"prices": [
{
"2015": 2
},
{
"2014": 3
},
{
"2013": 5
}
]
},
{
"name": "banana",
"prices": [
{
"2015": 1
},
{
"2014": 3
},
{
"2013": 4
}
]
}
]
}
I'm trying to create a map function (or several functions) in Javascript so that I can get the following 2 sets:
$scope.new_data = [
{
name: 'apple',
data: [5,3,2]
},
{
name: 'banana',
data: [4,3,1]
}
]
and
$scope.years = ['2013','2014','2015']
Perhaps something like this… but I don't know how to separate the key from the value:
$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();
];
});
Upvotes: 0
Views: 147
Reputation: 104795
You can do this all in one .map
function
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);
}
});
Upvotes: 1