Recently, I wrote a piece of code that is capable of exporting data into a CSV file. The data format it reads is structured as follows:
var data = [
['one', 'one is the first'],
['two', 'two is the second'],
['three', 'this is the third']
];
Below is the function responsible for executing this task:
function download_csv() {
var csv = 'Name,Title\n';
data.forEach(function(row) {
csv += row.join(',');
csv += "\n";
});
console.log(csv);
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv);
hiddenElement.target = '_blank';
hiddenElement.download = 'data.csv';
document.getElementById('export_btn_container').appendChild(hiddenElement);
hiddenElement.click();
}
Here is the corresponding HTML markup:
<button onclick="download_csv()">Download CSV</button>
<div id="export_btn_container" style="display:none;"></div>
Although the code above successfully caters to the provided format, the initial structure of my data looks like this:
"users":[
{
"id":"34",
"name":"namehere",
"user":{
"id":"56",
"username":"usernamehere",
"firstName":"firstnamehere",
"lastName":"lastnamehere"
},
"active":"yes"
}
]}
The question at hand is: how can I adapt the existing code to work seamlessly with the new data structure shown above?