0

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();
    ];
});

1 Answer 1

1

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);
    }
});
Sign up to request clarification or add additional context in comments.

3 Comments

Nice, that works for the data! How about the array of years?
That gives: ['2015','2014','2013','2015','2014','2013'] I think it's looping twice and also needs to be reversed
@murid -- Check the years variable - it should get rid of the duplicates.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.