简体   繁体   中英

How to reference data in second data set when loading via d3 v5 promises?

Using D3.js v5 I am trying to load in two json files. One file is a geo json file (a map of the US at the zipcode level) and the other is a data json file (data and information about each zipcode). Following dozens of examples, I have been able to view the map. But I just don't understand the syntax around promises and how to get the data from the two different files. It seems to mush it into one data set and I'm really confused about it.

I've tried accessing it as us[0] and us[1] (like in this example http://learnjsdata.com/read_data.html ) but it shows the first two rows of the first data set, instead of accessing the first and the second data set.

    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

        }

My goal is to access the data in the dataJSON file and set the fill for a specific zipcode by the ColorHex column for that zipcode. How would I reference the data array fro the dataJSON file?

The solution is very simple: remove those square brackets around us . It should be just:

function addZips(us) {

Explanation

By using those square brackets, as you're doing now...

function addZips([us]) {

... you are effectively destructuring when handling the parameters, getting just the first passed array. Look at this demo:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM