Eliminate unnecessary components during the JSON to CSV conversion process

I have a JSON data set that looks like this:

{"id":1,"name":"Sam","birthday":"12December","age":"15"},
{"id":2,"name":"Ash","birthday":"12January","age":"23"}

After passing the data through the function:

ConvertToCSV(data)

I can extract id, name, birthday, and age in the csv output. However, I want to exclude the birthday column from the conversion process to prevent it from appearing in the generated csv. How can I achieve this?

Current Output:

id | name | birthday   | age      
1  | Sam  | 12December | 15      
2  | Ash  | 12January  | 23       

Desired Output:

id | name | age
1  | Sam  | 15
2  | Ash  | 23

Below is the original code snippet:

ConvertToCSV(data) {
        var array = $.parseJSON('[' + data + ']');
        var fields = Object.keys(array[0]);
        var replacer = function(key, value) { return value === null ? '' : value } 
        var csv = array.map(function(row){
            return fields.map(function(fieldname){
                return JSON.stringify(row[fieldname], replacer)
            }).join(',')
        })
        csv.unshift(fields.join(',')) // add header column
        var str = csv.join('\r\n');
        return str;
    }

I tried to modify the function by adding the following code based on this reference:

for(var i = array.length - 1; i >= 0; i--) {
    var index = array[i].birthday;
    array[i].splice(index, 1);
}

However, the above code snippet does not produce the desired outcome. Can anyone assist me with this? Thank you!

Answer №1

Exclude the 'birthday' field from the list:

var fields = Object.keys(array[0])
  .filter(field => field !== 'birthday');

Complete code snippet (utilizing native JSON.parse):

var data = `
{"id":1,"name":"Sam","birthday":"12December","age":"15"},
{"id":2,"name":"Ash","birthday":"12January","age":"23"}
`;

var ConvertToCSV = (data) => {
    var array = JSON.parse('[' + data + ']');
    var fields = Object.keys(array[0]).filter(field => field !== 'birthday');
    var replacer = function (key, value) { return value === null ? '' : value }
    var csv = array.map(function (row) {
        return fields.map(function (fieldname) {
            return JSON.stringify(row[fieldname], replacer)
        }).join(',')
    })
    csv.unshift(fields.join(',')) // include header column
    var str = csv.join('\r\n');
    return str;
};

console.log(ConvertToCSV(data));    

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

Locating the elusive sequence number within a document

Greetings, I am currently trying to locate a missing number within an xml file but seem to be encountering some challenges. Any suggestions or ideas would be greatly appreciated. Example The file contains an <a> tag with various ids such as page-1, ...

Tips for extracting information from a Javascript Prompt Box and transferring it to a PHP variable for storage in an SQL database

My current issue involves a specific function I want my script to perform: before a user rejects an entry on the server side, the system needs to prompt a text box asking for the reason behind the rejection. The inputted reason should then be saved to a My ...

Experimenting with JavaScript within an Immediately Invoked Function Expression

My team leader is requesting that I encapsulate my JavaScript code within an Immediately-Invoked Function Expression (IIFE). However, I am struggling to use spyOn in my Jasmine spec file. How can I properly use spyOn on the following: (function(){ fu ...

Tips for utilizing event handlers such as (onSelect) in place of (change)

Is it possible to use EventEmitter to trigger an event when one or more elements are selected in the UI? I want a solution where the event is triggered once we change the selection. Thank you. <select multiple (change)="setSelected($event.target)"> ...

Refactor Print Preview Graph Display Issue within Nested Vue Component

I seem to be having trouble accessing this function properly due to an error. I am unsure of how to troubleshoot this issue and determine the correct solution. Any guidance would be greatly appreciated. The component PerformanceDonut.vue is located within ...

How can complex POST parameters be structured in a RESTful API?

For my current project, I am working on developing an application utilizing node.js along with express. This application involves a feature that allows users to subscribe to lists of items. Each subscription includes specific options such as minimum scores ...

JavaScript hack for improving slow scrolling experience with smooth scroll on Firefox

As a web application developer, I encountered a particular scenario where there are multiple position:fixed elements, canvases, and an overflow:scroll element. Unfortunately, scrolling in Firefox becomes extremely slow when smooth scrolling is enabled. Wh ...

What is the best choice for UI design framework when creating an ERP web application?

I am in the process of creating a web-based ERP application using Angular Material. However, I've noticed that each input element takes up a significant amount of vertical space on the page. This means if I have 15 input elements, I have to scroll dow ...

jQuery problem causes page to scroll when button is clicked

Is there a way to smoothly scroll to the second section of the page when a button is clicked using jQuery? $('.home_scroll_btn a').on('click', function(){ var scrollPosition = $('#intro-home').offset().top; $( ...

Traversing through elements with unique IDs in SwiftyJSON that are not part of an array

When calling an API, I sometimes receive an array of simple JSON objects. I handle these by parsing them using a basic "for i in count" loop and appending json[i]["city"] with SwiftyJSON. For instance: [{"city":"Lakefront","code":"NEW","country":"United S ...

Tips for incorporating a svg file into your React project

I am facing an issue with my custom React, Typescript, and Webpack project. I am trying to import a basic .svg file and utilize it in one of my components. However, Typescript is throwing the following error: Cannot find module I have tried installing s ...

When I test my jQuery scripts in jsfiddle, they run smoothly. However, they do not seem to work properly when I

My code is almost perfect, but the jQuery function is giving me trouble. It works fine in jsfiddle, but for some reason, it's not functioning in my HTML file. I don't believe extra characters are being added when copying from the HTML file. I hav ...

An error has occurred in the callback function for the watcher "function () { return this._data.$$state }": "Error: [vuex] It is forbidden to modify the vuex store state outside of a mutation"

Here is a screenshot of the error I encountered in the console This is the method that I am using The issue seems to be happening in mounted I have also included MapState in the Computed section While my code is currently functional, I am puzzled by th ...

Updating a JavaScript global variable within a click event function: A quick guide

I am currently using Javascript and jQuery to retrieve the mouse coordinates of a click event for use in other Javascript functions. The issue I am facing is that global variables set within an event function do not update outside the function, unlike glob ...

Ways to confirm that the function handed over as a prop to a Vue component operates asynchronously

How can I determine if a prop Function is asynchronous? Consider the following prop in my component: callbackFunction: { type: Function, default: null, }, Is there a way to validate this and ensure that the provided Function i ...

Navigating through a website that loads content dynamically with AJAX can be easily done by

Having an issue with scraping data from a website using jQuery AJAX. There are 300 links to scrape, but the site only shows 50 at a time, requiring scrolling to load more. Can someone assist me with this? var baseURL = "https://hr.myu.umn.edu/psc/hrp ...

Resizing a scrollable list using React Refs and UseLayoutEffect

Essentially, my issue stems from having a scrollable list with a set maximum height of '100vh'. I also have a detail card beside the list that contains accordion components. When one of these accordions is expanded, it increases the height of the ...

"Exploring the process of integrating angular-xeditable into a MeanJS project

I recently attempted to install angular-xeditable from the link provided, but encountered issues while trying to reference the JavaScript files in layout.html after downloading it with bower. According to the documentation, these files should be added auto ...

Integrate CSS and JavaScript files into Node Express

I am facing an issue including my CSS file and JavaScript file in a node-express application, as I keep getting a 404 not found error. Here is the code snippet that I am using: 1. In server.js var http = require('http'); var app = require(' ...

Ways to alter the div post user authentication

I'm in the process of developing a website with a single-page application setup. I'm utilizing Node.js for the backend and Angular for the frontend. The challenge I'm facing is displaying a specific div when a user is not logged in, and swit ...