从D3函数返回js数据集

时间:2016-10-06 09:55:43

标签: javascript asynchronous d3.js

我获得了以下工作代码:

var datasetBarChart = [{
    group: "X",
    category: "Oranges",
    measure: 100
}, {
    group: "Y",
    category: "Apples",
    measure: 200
}];

// set initial group value
var group = "X";

function datasetBarChosen(group) {
    var ds = [];
    for (x in datasetBarChart) {
        if (datasetBarChart[x].group == group) {
            ds.push(datasetBarChart[x]);
        }
    }
    return ds;
}

我没有对datasetBarChart中的数据进行硬编码,而是将数据移动到如下所示的csv:

group,category, measure
X,    Oranges,  100
Y,    Applies,  200

现在我正在尝试修改该功能 - 它仍然需要return ds; - 以下是我的一个尝试不起作用:

function datasetBarChosen(group) {
    var ds = [];

    d3.csv("http://ourServer/testingtesting/DThree/datasetBarChart.csv", function(rows) {
            for (x in rows) {
                if (rows[x].group == group) {
                    ds.push(rows[x]);
                }
            }
        }

    return ds;
}

这是另一次失败的尝试!!

function datasetBarChosen(group) {
    var ds = [];

    d3.csv("http://ourServer/testingtesting/DThree/datasetBarChart.csv", function(rows) {

        ds = rows.map(function(d) {
                //each d is one line of the csv file represented as a json object                
                if (d.group == group) {
                    return {
                        "group": d.group,
                        "category": d.category,
                        "measure": +d.measure
                    }
                };
            })

    }

    return ds;
}

....是以下哪一种关闭?

1 个答案:

答案 0 :(得分:2)



twitter api

function datasetBarChosen(group, process) {//this can be refactored more
  var ds = [];
  d3.csv("https://raw.githubusercontent.com/openmundi/world.csv/master/countries(204)_olympics.csv")
    .row(d => d["Code"] === group ? d : false)//get only items with code===group
    .get(process);

}

function doThisWithResult(error, rows) {
  console.log(rows);
  //write all your logic to do with returned data here;
  //or call other functions from here passing data
}

datasetBarChosen("ZIM", doThisWithResult);




使用Babel

转换为es5
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>