简体   繁体   中英

How to map key and value from array of objects?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM