Markcce Eros Markcce Eros - 18 days ago 5
Javascript Question

Javascript Amend/convert code that reads array to work with object data

I have some code which will export some day into a csv file with reads this data format:

var data = [
['one', 'one is the first'],
['two', 'two is the second'],
['three', 'this is the third']
];


and here is the function that does the job:

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();
}


and the html part:

<button onclick="download_csv()">Download CSV</button>
<div id="export_btn_container" style="display:none;"></div>


The code above works well but the data I have the start with looks like this:

"users":[
{
"id":"34",
"name":"namehere",
"user":{
"id":"56",
"username":"usernamehere",
"firstName":"firstnamehere",
"lastName":"lastnamehere"
},
"active":"yes"
}
]}


My question is...how can I use the code above with the data just above?

Answer

You have to iterate the users property which is an array. For each user you get the properties you need one by one

var data = {
  "users": [{
    "id": "34",
    "name": "namehere",
    "user": {
      "id": "56",
      "username": "usernamehere",
      "firstName": "firstnamehere",
      "lastName": "lastnamehere"
    },
    "active": "yes"
  }]
}

function download_csv() {
  var csv = 'Id,Name,Username,Firstname,Lastname,Active\n';
  data.users.forEach(function(user) {
    csv += user.id + ",";
    csv += user.name + ",";
    csv += user.user.username + ",";
    csv += user.user.firstName + ",";
    csv += user.user.lastName + ",";
    csv += user.active;
    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();
}
<button onclick="download_csv()">Download CSV</button>
<div id="export_btn_container" style="display:none;"></div>

If you dont know the names of the keys you can use this code

var data = {
  "users": [{
    "id": "34",
    "name": "namehere",
    "user": {
      "id": "56",
      "username": "usernamehere",
      "firstName": "firstnamehere",
      "lastName": "lastnamehere"
    },
    "active": "yes"
  }]
}

function download_csv() {
  var csv = 'Id,Name,ID,Username,Firstname,Lastname,Active\n';
  data.users.forEach(function(user) {
    //iterate all keys
    Object.keys(user).forEach(function(key){
      //is object
      if(typeof user[key] === 'object'){
        //iterate keys of nested object
        Object.keys(user[key]).forEach(function(secondKey){
          csv += user[key][secondKey] + ",";
        })
      }else{
       csv += user[key] + ","; 
      }  
    })
    //remove last comma
    csv = csv.slice(0, -1);
    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();
}
<button onclick="download_csv()">Download CSV</button>
<div id="export_btn_container" style="display:none;"></div>