Reconfigure the code to process object data instead of an array in JavaScript

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?

Answer №1

To extract the necessary information, you have to loop through the users array in the data object and access each property individually.

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 are unsure about the keys' names, you can use the following code snippet:

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) {
    Object.keys(user).forEach(function(key){
      if(typeof user[key] === 'object'){
        Object.keys(user[key]).forEach(function(secondKey){
          csv += user[key][secondKey] + ",";
        })
      }else{
       csv += user[key] + ","; 
      }  
    });
    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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Bootstrap's modal-backdrop element presents a striking fade effect as it

Issue I am facing a problem related to Bootstrap, specifically with a modal in my HTML file. Whenever I call the modal, it appears with a fade-in effect. The code for my modal: <div class="modal fade" id="exampleModal" tabindex=& ...

Is it possible to load conditionally if the browser is switched to Developer Mode?

Currently, I am in the process of debugging my code using Chrome Dev Tools. I have been contemplating whether it is possible to load JavaScript only when DevTools are active in Chrome and ignore it otherwise. This way, I can include debugging logic in my ...

Make sure to leave a space after a period in a sentence, but do

My question is about fixing spacing issues in text, specifically sentences that lack spaces after a dot. For example: See also vadding.Constructions on this term abound. I also have URLs within the text, such as: See also vadding.Constructions on th ...

Searching for similar but not identical results using Knex.js

I am seeking a solution to retrieve similar posts without including the post itself. Here is my approach: export async function getSimilars(slug: string) { const excludeThis = await getBySlug(slug) const posts = await knex('posts') .whe ...

Remove the pop-up using its unique identifier, element, or style class

I recently launched a free hosting site, but I'm encountering an issue where an ad for the site keeps appearing upon loading. I need to find a way to remove the specific rows that contain this ad. Specifically, I want to delete the ****BOLD**** rows, ...

Can someone please help me understand why my CSS transform scale isn't functioning properly?

I've developed a JavaScript function that enlarges a button and then smoothly shrinks it back to its original size. The function successfully changes the color of the button to blue, but for some reason, it's not working with the transform prope ...

Solution for Organizing Tables

I've sourced data from various JSON API links and displayed it in a table. Currently, my code looks like this: <script src="js/1.js"></script> <script src="js/2.js"></script> Above this code is the table structure with <t ...

Separate every variable with a comma, excluding the final one, using jQuery

I've developed a script that automatically inserts checked checkboxes and radio options into the value() of an input field. var burgerName = meat + " with " + bread + " and " + onion + tomato + cheese + salad; $('#burger-name').val(burger ...

Identify the specific element using a designated data attribute

Having trouble figuring out how to select a specific element with a particular data attribute. In my situation, I want to target the a element with class="zoom-image" and data-order-item-id="<?=$order_item_id ?>". Here is the HTML/PHP code snippet ( ...

The "checked" property is absent in the ASP.NET checkbox within the gridview

In my asp.net gridview control, the checked property seems to be missing. I am trying to access the checked property using jquery Gridview structure: <Columns> <asp:TemplateField> <ItemTemplate> ...

Converting XML to JSON in a Node.js application

I recently read an article on that explained the conversion process clearly, but unfortunately it's not working for me. Let me provide you with the code snippet: function parseXml(xml) { var dom = null; if (window.DOMParser) { try ...

What steps can I take to prompt a ZMQ Router to throw an error when it is occupied?

In my current setup, I have a configuration with REQ -> ROUTER -> [DEALER, DEALER... DEALER]. The REQ acts as a client, the ROUTER serves as a queue, and the DEALER sockets are workers processing data and sending it back to ROUTER for transmission to ...

When transferring a PHP array into a JS array, each letter of the values within the array becomes separated into its own element

Here is the provided code snippet: <?php $array = array('RANAJI', 'YAARA MAULA', 'AARAMBH', 'AISI SAZAA', 'SHEHER', 'BEEDO', 'DUNIYA', 'RAAT KE MUSAFIR'); foreach ($array a ...

Button activated on second click

As I am working on a project, I encountered an issue with two buttons and one input field. The input field is supposed to take the value of the clicked button, but currently, the function works only after the second click on the button. I have tried using ...

Is there a way to sort through a JSON object using JavaScript?

I have a JSON string that looks like this: { "Animal":{ "Cat":20, "Dog":10, "Fish":5 }, "Food":{ "Pizza":500, "Burger":200, "Salad" ...

Retrieve a specific value from an array within Firestore

I am facing an issue where I can only retrieve the values I need from the array by adding a specific string like "اقلام" or "سبورة". However, I want the value to be passed as a prop from another component or screen. Is there a way to resolve this ...

React Component that closes when it loses focus

In my React project, I am working on creating a custom select2 style component. Most of the functionality is complete, but I am struggling with figuring out how to hide the result box when the user clicks away. Here is the render method: render() { l ...

JavaScript causing values to disappear when the page refreshes

When a user hovers over ImageButtons, I use Javascript to change the ImageUrl. However, on submitting the form, the updated ImageUrl property is not reflected in the code behind. Similarly, I also dynamically update a span tag using Javascript, but its alt ...

Clicking on an element triggers the addition of a class, and the newly

Once the page has finished loading, I am able to utilize jQuery to add a specific class in the following way. $(document).ready(function() { $("#parent").click(function(){ $(".child").addClass("active"); }); }) ...

Finding a workaround for the absence of a leftToggle feature in ListItem component of Material-UI

Is there a way to move the toggle element to the other side in Material-UI's listItem without using the leftToggle option? The documentation does not specify a leftToggle attribute, so I am looking for alternative solutions. I would like to align the ...