D3:使用.map()重新排列数据数组

时间:2014-07-02 19:50:32

标签: javascript arrays d3.js

如果我有这样的数据......

var dataset = [
    { apples: 5, oranges: 10, grapes: 22 },
    { apples: 4, oranges: 12, grapes: 28 },
    { apples: 2, oranges: 19, grapes: 32 },
    { apples: 7, oranges: 23, grapes: 35 },
    { apples: 23, oranges: 17, grapes: 43 }
];

我如何使用.map()方法重新排列数据,使其成为一个数组数组,每个数组代表一个类别(苹果,橙子,葡萄),该数组中的每个对象都是数据。 x是ID标记。

var dataset = [
    [
            { x: 0, y: 5 },
            { x: 1, y: 4 },
            { x: 2, y: 2 },
            { x: 3, y: 7 },
            { x: 4, y: 23 }
    ],
    [
            { x: 0, y: 10 },
            { x: 1, y: 12 },
            { x: 2, y: 19 },
            { x: 3, y: 23 },
            { x: 4, y: 17 }
    ],
    [
            { x: 0, y: 22 },
            { x: 1, y: 28 },
            { x: 2, y: 32 },
            { x: 3, y: 35 },
            { x: 4, y: 43 }
    ]

];

2 个答案:

答案 0 :(得分:3)

执行此操作的一种方法是为每个键(水果),使用map创建该水果的所有对象:

newDataset = ["apples", "oranges", "grapes"].map(function(n){
    return dataset.map(function(d, i){
               return { x: i, y: d[n] };
           });
    });

请注意,传递给i的匿名函数中的mapdataset数组的索引,因此可以用作ID。

答案 1 :(得分:0)

您也可以使用.reduce()

一次完成此操作
dataset.reduce(function(previous, current, index, array){
    return Object.keys(current).map(function(d, i){
        return previous[i].concat([{'x' : i, 'y' : current[d]}]);
    });
}, [[],[],[]]);

这是从一个空的数组骨架开始,每次迭代都会在每个数组中填充一个内部对象。

当然,这涉及在构建新数组时循环遍历每个对象内部的键,因此循环本身不比mdml的答案更有效,但它没有初始赋值,因此是一个操作更有效率,因此显然是优越的答案:P