1

I have managed to write a script to export data from a GET request in Javascript to CSV. However I have a unit variable that has more fields (time, altitude, latitude, o3, co2, ch2o). How can I create a CSV with more columns with the values taken from the script?

So far I have managed to create a CSV with multiple headers, but I don't know how to populate the rows of the CSV with data. I have managed to fully populate only one column.

In the below function, I have used unit[Object.keys(unit)[4]] to only get co2 data. How can I append data to every column?

function download_csv(data, sensor) {
  var csv = 'Day, altitude, latitude, o3, co2, ch2o\n';
  for (var index in data) {
    if (!data.hasOwnProperty(index)) continue;
    var unit = data[index];
    csv += unit[Object.keys(unit)[4]];
    csv += "\n";
  }
  var hiddenElement = document.createElement('a');
  hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv);
  hiddenElement.target = '_blank';
  hiddenElement.download = sensor + '.csv';
  hiddenElement.click();
}

Data has this format: enter image description here

2
  • Can you give an example for data? Commented Apr 21, 2020 at 8:38
  • @wederer I have updated the question with an image of the data. Commented Apr 21, 2020 at 8:43

1 Answer 1

5

Assuming the data argument contains an array of objects which you use to build the CSV data, you can use Object.keys() and Object.value() to dynamically build the data. Using this method it does not matter what the key names are, or how many of them is contained in the data.

function download_csv(data, sensor) {
  let csvHeader = Object.keys(data[0]).join(',') + '\n'; // header row
  let csvBody = data.map(row => Object.values(row).join(',')).join('\n');

  var hiddenElement = document.createElement('a');
  hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csvHeader + csvBody);
  hiddenElement.target = '_blank';
  hiddenElement.download = sensor + '.csv';
  hiddenElement.click();
}

let data = [{
  lorem: 'ipsum',
  foo: 'bar',
  fizz: 'buzz'
}];
download_csv(data, 'foobar');

One thing to note if you need to support legacy browsers is that Object.values is unsupported in IE. There is a polyfill available, though.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.