d3为现有的json数据添加新的键值

时间:2014-05-28 04:43:12

标签: javascript d3.js nvd3.js

我有一个想要寻求你的专业知识的问题。

这是我的JSON数组:

[{
    key : "Group 0",
    values : [{
        x : 0.12817352913159197,
        y : 4.360475517778741,
        size : 0.8945912778023366
    }, {
        x : -1.8709283296311146,
        y : 1.4047025584603734,
        size : 0.3621509721039796
    }]
}, {
    key : "Group 1",
    values : [{
        x : 0.6574795166435595,
        y : -0.6037258352005531,
        size : 0.0942101986534386
    }, {
        x : -0.4951370796031603,
        y : -0.18739226817326712,
        size : 0.8843348380774309
    }]
}]

我将此传递给scatterChart,所以里面的数据包含这个,现在我想为每个值添加形状,最终我希望它像这样在图表数据中:

[{
    key : "Group 0",
    values : [{
        x : 0.12817352913159197,
        y : 4.360475517778741,
        size : 0.8945912778023366,
        shape : "circle"
    }, {
        x : -1.8709283296311146,
        y : 1.4047025584603734,
        size : 0.3621509721039796,
        shape : "diamond"
    }]
}, {
    key : "Group 1",
    values : [{
        x : 0.6574795166435595,
        y : -0.6037258352005531,
        size : 0.0942101986534386,
        shape : "circle"
    }, {
        x : -0.4951370796031603,
        y : -0.18739226817326712,
        size : 0.8843348380774309,
        shape : "diamond"
    }]
}]

如何使用d3或nvd3实现此目的?

1 个答案:

答案 0 :(得分:0)

如果我理解你的问题

var demo = [{
    key: "Group 0",
    values: [{
        x: 0.12817352913159197,
        y: 4.360475517778741,
        size: 0.8945912778023366,
    }, {
        x: -1.8709283296311146,
        y: 1.4047025584603734,
        size: 0.3621509721039796,
    }]
}, {
    key: "Group 1",
    values: [{
        x: 0.6574795166435595,
        y: -0.6037258352005531,
        size: 0.0942101986534386,
    }, {
        x: -0.4951370796031603,
        y: -0.18739226817326712,
        size: 0.8843348380774309,
    }]
}];

for (var i = 0, j = demo.length; i < j; i++) {
    group = demo[i]['values'];
    for (var x = 0, y = group.length; x < y; x++) {
        if (x == 0) {
            // Assuming the first is always circle
            group[x]['shape'] = "circle";
        } else {
            // Assuming the second is always diamond
            group[x]['shape'] = "diamond";
        }
    };
};

console.log(demo);

有一个正常工作的版本here

希望有所帮助