-2
function readJson(sample) {
    d3.json("samples.json").then((data) => {
        var extract = data.metadata
        var emptyArray = extract.filter(object => object.id == sample);
        var finalArray = emptyArray[0];
        var Visual = d3.select("#sample-metadata");

        Object.entries(finalArray).forEach(([key, value]) => {
            Visual.append("h6").text(`${key} : ${value}`);
        });
    });
}

My friend handed over this code for me but I'm having a hard time understanding the arrow functions. Can anyone explain what this function is performing? The ID and JSON files are saved as separate files.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122

1 Answers1

0

The arrow functions are being used as anonymous callback functions on the methods .then, filter and .forEach.

You could just as well write it like this:

function readJson(sample) {
    // .json returns a promise which resolves to a json object assigned the name data
    // .then allows you to chain asynchronous functions with other async or synced functions
    d3.json("samples.json").then(function(data){
        var extract = data.metadata
        // Filter all the objects which satisfy the provided testing function
        var emptyArray = extract.filter(function(object){
            return object.id == sample
        });
        var finalArray = emptyArray[0];
        var Visual = d3.select("#sample-metadata");

        // For each key/value pair in finalArray execute the provided function
        Object.entries(finalArray).forEach(function([key, value]){
            Visual.append("h6").text(`${key} : ${value}`);
        });
    });
}
lawrence-witt
  • 8,094
  • 3
  • 13
  • 32