如何映射对象数组中的键和值?

时间:2016-01-12 16:55:08

标签: javascript arrays angularjs

我通过$ 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();
    ];
});

1 个答案:

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