将json响应转换为可用于d3漏斗图的数组

时间:2014-03-11 02:59:23

标签: javascript json d3.js

示例json:

{
    "json_data": [
        {
            "budget": 1000,
            "Actual": "3468.000 "
        },
        {
            "budget": 2000,
            "Actual": "7905.000 "
        },
        {
            "budget": 3000,
            "Actual": "7454.000 "
        },
        {
            "budget": 4000,
            "Actual": "3671.000 "
        },
        {
            "budget": 5000,
            "Actual": "5875.000 "
        },
        {
            "budget": 6000,
            "Actual": "6157.000 "
        },
        {
            "budget": 7000,
            "Actual": "7520.000 "
        },
        {
            "budget": 8000,
            "Actual": "2251.000 "
        },
        {
            "budget": 9000,
            "Actual": ""
        },
        {
            "budget": 10000,
            "Actual": ""
        },
        {
            "budget": 11000,
            "Actual": ""
        },
        {
            "budget": 12000,
            "Actual": ""
        }
    ]
}

到这种格式的阵列:

vardata=[
    [
        'VideoViews',
        1500
    ],
    [
        'Comments',
        1000
    ],
    [
        'VideoResponses',
        900
    ],
    [
        'VideoViews',
        1500
    ],
    [
        'Comments',
        1000
    ],
    [
        'VideoResponses',
        900
    ]
];

1 个答案:

答案 0 :(得分:0)

这就是我可能会这样做的。简而言之,您正在尝试将对象数组转换为数组数组。

output = [] // this will become  an array of array

// assuming json_data is store in example    

for (var i=0;i< (example['json_data']).length;i++){
    var entry = exmple['json_data'][i] 
    output.push(['budget', entry['budget']]);
    output.push(['Actual',entry['Actual']]);

}

console.log(JSON.stringify(output))
// [["budget",1000],["Actual","3468.000 "],["budget",2000],\
// ["Actual","7905.000 "],["budget",3000] ... ] //