如何通过 d3 v5 承诺加载时引用第二个数据集中的数据



使用 D3.js v5 我正在尝试加载两个 json 文件。 一个文件是地理 json 文件(邮政编码级别的美国地图(,另一个是数据 json 文件(有关每个邮政编码的数据和信息(。 在几十个例子之后,我已经能够查看地图。 但我只是不明白承诺的语法以及如何从两个不同的文件中获取数据。 它似乎把它混在一个数据集中,我真的很困惑。

我尝试以us[0]和us[1]的身份访问它(如本例 http://learnjsdata.com/read_data.html(,但它显示了第一个数据集的前两行,而不是访问第一个和第二个数据集。

    var loadJSON = d3.json("/json/zips_us_topo.json");
    var dataJSON = d3.json("/json/CustomersByZip.json",
        function(d){
            zipcodeData.set(d.Zipcode, d.TotalPatients,d.ColorHex);
        });
    //Promise
    Promise.all([loadJSON, dataJSON]).then(addZips).catch(console.log.bind(console));
    function addZips([us]) {
        var myJSON = JSON.stringify(us);
        console.log(myJSON.substring(0,200)); // Returns first 200 characters of loadJSON file, so I know I can just reference it with "us".
        console.log(dataJSON); // displays "Promise {<resolved>: {...}}
        console.log(loadJSON); // displays "Promise {<resolved>: Array(28355)}" so it loaded the dataJSON data but how do I reference it?
        console.log(us[0]); // displays "undefined"
        console.log(us[1]); // displays "undefined"
        console.log(us[0][0]); // TypeError: Cannot read property '0' of undefined
        console.log(us[1][0]); //TypeError: Cannot read property '0' of undefined
        }

我的目标是访问 dataJSON 文件中的数据,并通过该邮政编码的 ColorHex 列设置特定邮政编码的填充。 我将如何引用数据JSON文件的数据数组?

解决方案非常简单:删除us周围的方括号。它应该只是:

function addZips(us) {

解释

通过使用这些方括号,就像您现在所做的那样...

function addZips([us]) {

。在处理参数时,您正在有效地解构,只获得第一个传递的数组。看看这个演示:

const a = [[42], [17]];
foo(a);
bar(a);
function foo(x) {
  console.log("Without brackets: " + x);
}
function bar([x]) {
  console.log("With brackets: " + x)
}

相关内容

最新更新