Having difficulty converting a list of intricate objects into a CSV format

I am faced with a challenge of handling an array of complex objects, some of which may contain arrays of more objects. My goal is to convert this data into a CSV file. However, whenever there is a list of objects, the information appears as [object Object]. For instance, if a person has multiple email addresses, I would like each email to be displayed on a separate line. Similarly, addresses may need to be concatenated into a single string format, like "France, Paris, someStreet 15".

You can find the code for this task in this pen.

Below is a snippet of the data:

var names = [
        {
          Name: [{First: "Peter", Last:"john"}],
          WorkPlace: [{Company: "Intel", emails: ["<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="94fef5f7ffd4fdfae0f1f8f8baf7fbf9">[email protected]</a>","<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5637323b3b3a16">[email protected]</a>"]}],
          Age: 33.45,
          Adress: [{Country:"UK", city: "London", street:"Oak", strtNumber:16},
                  {Country:"Italy", city: "MIlan", street:"Zabin", strtNumber:2}]
        },
        {
            Name: [{First: "jack", Last:"Smith"}],
          WorkPlace: [{Company: "Intel", emails: ["<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="86ece7e5edc6efe8f2e3eaeaa8e5e9eb">[email protected]</a>","<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e180858c88a1888f95848d8dcf828e8c">[email protected]</a>"]}],
            Age: 30,
          Adress: [{Country:"Portugal", city: "Lisbon", street:"crap", strtNumber:144},
                  {Country:"Greece", city: "Athenes", street:"Hercules", strtNumber:55}]
        },
        {
            Name: [{First: "jon", Last:"snow"}],
          WorkPlace: [{Company: "Intel", emails: ["<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b2d8d3d1d9f2dbdcc6d7dede9cd1dddf">[email protected]</a>","<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f091949d99b0999e84959c9cde939f9d">[email protected]</a>"]}],
            Age: 50,
          Adress: [{Country:"Middle earth", city: "Winterfell", street:"raven", strtNumber:4345},
                  {Country:"Narnia", city: "Jacksonvile", street:"Great crap", strNumber:34}]
        },
    ];

Currently, the output looks like this:

https://i.sstatic.net/Xjh7t.png

Answer №1

In the convertArrayOfObjectsToCSV method, there is a mistake where the 'item[key]' result is an array when dealing with 'Name'. To properly handle this array, you need to specify how to process it further, otherwise it will be output as [object Object]. You will need to access the element using item[key][index] and then iterate over its properties to print them as required.

Answer №2

The [object Object] signifies that additional conversion is necessary to achieve the desired result.

Check out an updated CodePen featuring a demonstration of the conversion process.

The conversion method provided utilizes Object.values() to convert all data:

function parseArrayOfObjects(arrayOfObj){
  return arrayOfObj.map(item => 
    Object.values(item).join(" ")) // convert each array item to its values
    .join(" ") // convert final array to string
    .replace(",", " "); // eliminate any commas to maintain csv format
}

Of course, you may need to tailor the conversion to suit your specific requirements.

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

Ways to increase the values in a textbox

My task involves handling checkboxes that are populated with data from a database. The goal is to have certain checkboxes pre-checked based on the retrieved data, and if any are not checked, their values should be entered into a textbox. For instance, con ...

What could be causing the lack of change in direction for the initial function call?

There appears to be an issue with image(0) and image(1) in this array that I can't quite understand. The console output shows: i=5; div class="five" id="slides" i=0; div class="one" id="slides" i=1; div class= ...

Is there a way to access and troubleshoot the complete source code within .vue files?

I've been struggling for hours trying to understand why I'm unable to view the full source of my .vue files in the Chrome debugger. When I click on webpack://, I can see the files listed there like they are in my project tree, but when I try to o ...

Retrieve the keys of an interface using generic methods

Recently, I encountered a challenge with a function that utilizes generics. The specific generic in question is <T extends anInterfaceName>. Struggling to retrieve the keys of the interface used in T within the function, my quest for a solution led m ...

The AJAX call in PHP is echoing JavaScript code that seems to be malfunctioning

Currently working on an AJAX page using php, where I plan to output a section of JS code upon completion. Despite having the JS code within the HTML page, it is not functioning properly. Any suggestions on how to get it to work? ...

Having trouble with my basic AJAX request; it's not functioning as expected

I am currently diving into the world of Ajax and I've hit a roadblock: 1. HTML : <body> <form> Username: <input type="text" id="username" name="username"/> <input type="submit" id="submit" /> </form> <scrip ...

I pressed the button but the globalCompositeOperation isn't working as expected. How can I make it function correctly to achieve the desired output like the second canvas?

<!DOCTYPE html> <html> <head> <title>Canvas Compositing Tutorial</title> </head> <body> <canvas id="myCanvas" width="200" height="200" style="border: 1px solid"></canvas> <br> <butt ...

Node.js module mishap

In the package.json file I'm working with, these are the content of my dependencies: "devDependencies": { "chai": "^4.1.2", ... "truffle": "4.1.3" } A new NodeJS script called getWeb3Version.js was created: let web3 = require("web3" ...

Avoiding unlimited re-renders when using useEffect() in React - Tips and Strategies

As a new developer, I recently built a chat application using socket io. In my code, I have the useEffect hook set to only change when the socket changes. However, I also have setMessage within the body of useEffect(), with socket as a dependency. Unfortun ...

The error middleware in Express is not defined

I'm facing an issue where the Express API error messages are returning as undefined on the frontend. This is preventing me from displaying proper error messages to alert users. Interestingly, the error messages seem to appear fine in the developer to ...

Can I assign a value from the tagModel to ngx-chips in an Angular project?

HTML code: <tag-input class="martop20 tag-adder width100 heightauto" [onAdding]="onAdding" (onAdd)="addInternalDomain($event)" type="text" Ts code: addInternalDomain(tagTex ...

Add more functionality to the server.js script

I have the server.js file, which serves as the entry point for my Node application and is responsible for invoking three different functions (these functions are only called once when the server is up, such as creating child processes, validation, etc), wh ...

Automatically update certain attributes of an object with Spring MVC's auto-refresh feature

Currently, I have a table in JSP where I am populating all object attributes using Spring MVC. The backend is providing a list of DTO's which are then being added to the ModelView. In the JSP, we iterate through this DTO list and display it in the tab ...

Creating TypeScript declaration file for exporting JavaScript function

I'm a beginner with TypeScript and I want to learn how to create a declaration file for a custom JavaScript function. I attempted to do this, however, I encountered an error stating "Could not find a declaration file for module './main'." Ad ...

JQuery ajax fails to trigger the success function

Upon using an ajax request to insert data into the database, I encountered an issue where the button message did not update after the submission was successful. Initially, I set the button text to Please wait... upon click, and intended to change it to Don ...

When attempting to integrate Bootstrap 5 with Laravel, you may encounter an issue where the "bootstrap is

I've come across a common issue where none of the solutions seem to work for me. Currently, I am working with Laravel 10 and Vite, and have successfully installed Bootstrap using NPM. Although the configuration was correct for using Bootstrap CSS and ...

The function dispatch is not recognized and will be removed from the database. An error will be generated indicating that dispatch is not a valid function

There seems to be an issue with the delete function in Ticket Actions as it is giving an error that dispatch is not a function. The goal here is to enable users to delete specific tickets by clicking on them and also provide an option to edit the ticket. ...

How to retrieve a refined selection of items

In my scenario, there are two important objects - dropdownOptions and totalItem https://i.sstatic.net/VreXd.png The requirement is as follows: If 12 < totalItems < 24, then display "Show 12, Show 24" If 24 < totalItems < 36, only show "Show ...

What is the best approach to dynamically update CSS using onChange in TypeScript?

I am facing an issue with 2 input fields on my website. I want to create a functionality where if a user enters data into one field, the CSS of the other field changes dynamically. For instance, I would like to change the class "changeAmount" to "display:n ...

There is no imageURL property available for this type

Everything was running smoothly on my local project, but encountered errors upon deploying to Vercel: The properties imageURL and alt do not exist on type {} Despite attempting to define the types based on suggestions from Stack Overflow, the issues per ...