converting a CSV string into a JSON array using AngularJS

My data is in a comma-separated format:

"HotelName","Remained","Date"
"Maxx","4","Jun 26 2016"
"Voyage","3","Jun 24 2016"

I am looking to convert this into a JSON array as shown below. How can I achieve this using my JavaScript code?

[
  {
    HotelName:"Maxx",
    Remained:"4",
    Date:"Jun 26 2016"
  },
  {
    HotelName:"Voyage",
    Remained:"3",
    Date:"Jun 24 2016"
  }
]

Answer №1

To start, create a new array using var example = []. Next, populate the array by pushing data into it as such example.push({ key : "value"}). Finally, convert the array to JSON format using

json_example = JSON.stringify(example)
. This is a handy trick I often use in my web development projects.

Answer №2

When dealing with a String, one possible approach is to consider splitting it into parts.

let dataLines = data.split('\n');
let dataArray = [];

if(dataLines.length > 0){
    let titles = dataLines[0].split(',');
    
    for(let i=1; i<dataLines.length; ++i){
        let objData = dataLines[i].split(',');
        let newItem = {};
        
        // It's important to ensure that titles and objData have the same length
        for(let j=0, j<titles.length; ++j){
            newItem[titles[j]] = objData[j];
        }
        
        dataArray.push(newItem);
    }
}

Answer №3

It appears that the data received from the remote server is a JSON object converted into a string.

// This might be a CSV data string retrieved from your server;
var csvData = "\"HotelName\",\"Remained\",\"Date\"\"Maxx\",\"4\",\"Jun 26 2016\",\"Voyage\",\"3\",\"Jun 24 2016\"";

var NUMBER_OF_COLUMNS = 3;
var columns = [];
var arrayData = [];

// Removing double quotes in csvData and parsing it into an array;
csvData = csvData.replace(/"/g, "").split(',');
columns = csvData.slice(0, NUMBER_OF_COLUMNS);
csvData = csvData.slice(NUMBER_OF_COLUMNS);

var rowObject = {};
csvData.forEach(function(item, index) {
  rowObject[columns[index % (NUMBER_OF_COLUMNS)]] = item;
  if (index % (NUMBER_OF_COLUMNS) == 2) {
    arrayData.push(rowObject);
    rowObject = {};
  }
})

console.log(arrayData);
/*
  [ 
    {
      DataMaxx: "Voyage",
      HotelName: "4",
      Remained: "Jun 26 2016"
    }
  ]
*/

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

The JSON schema is failing to validate the mandatory attribute

I have been working on coding a Json Schema that defines the layout created by the user. Within this schema, I have defined different properties such as "stdAttribute" and "stdItem" with specific types and required attributes. However, when I set certain d ...

HTML form with a dropdown menu

Imagine you have a HTML form containing two dropdown lists. The first dropdown is labeled "country" and contains a list of countries. The second dropdown, labeled "cities," should be dynamically populated based on the country selected. What is the best ...

Is there a way to turn off predictive text for reCAPTCHA on my mobile device?

Using reCAPTCHA on a sign-up form can get frustrating on mobile devices, with constant dictionary word suggestions while typing. I am aware of how to disable this feature for normal input fields by adding attributes through JavaScript, but shouldn't ...

How can I transmit information to the model without relying on query string parameters in Express?

Currently, I am working with two controllers - authController and onboardingController. The authController communicates with the onboardingController using the following line of code: res.redirect('/onboarding/info?profileId=' + profile.id + &ap ...

Create a Sequelize query to search for results that are similar to a specific

I am currently working on constructing a search query in Sequelize to query a MySql database. My goal is to search for a specific text across multiple fields, including JSON data. In the JSON field, I want to search for the text anywhere within the data, n ...

Locating the JSON path within an object

Need help with checking if a specific path is present in a JSON object? var data = { "schemaOne": { "name": "abc", "Path": "i.abc", "count": 5347, "subFolders": [ ] }, "schemaTwo": { "name": "cde", "Path": "i.cde", " ...

Assign increasing values within an array

Is there a way to efficiently update multiple values in an array by mapping through them? I want to select and change all of them simultaneously. state.formData.forEach(item => { item.EndDate = nextDayIfSelected; }); ...

Is there a way to get rid of the tiny black line beside the Instagram icon?

Here is the display on my website This is the code that was used I am struggling to identify the source of the small black "-" line next to the Instagram icon logo. ...

Redux: streamlining containers, components, actions, and reducers for seamless organization

Here's the question: When working on a large React/Redux application, what is the most effective and sustainable method for organizing containers, components, actions, and reducers? My take: The current trend leans towards organizing redux elemen ...

Struggling to locate a route for the React styled components image

I'm having trouble locating the correct path for the image in my React styled components. I believe the path is correct, but could the issue be related to styled-components? Check it out here import styled from "styled-components"; export defaul ...

Trigger a function upon the initial keypress event detected on an input field

I am facing an issue with an input element that has an onkeypress event triggering a function called change(). Strangely, the function does not execute on the very first keypress. I notice that I have to input 55 instead of just 5 for the function to updat ...

Creating individual components for <select> and <option> elements in ReactJS

I am uncertain about how references function when the select and option tags are used together. When I split them into separate React components, they stop working. How can I resolve this issue? Here is a basic example: <select> {() => ( ...

Perform a task upon clicking the JavaScript menu

Implementing dropdown menu items using a text link with JavaScript and CSS. You can view a demo here. I am looking to trigger an action when each menu item is clicked. Currently, they are not behaving as expected. HTML: <span class="inline-dropdown- ...

Transforming dynamic class based on state value from React to TypeScript

I'm trying to implement this React function in TypeScript, but I'm encountering errors. const ListItem = ({ text }) => { let [showMore, setShowMore] = useState(false); return ( <div className="item"> ...

Dynamically populate 7 select boxes with options using JQuery

I have a webpage that includes 14 different dropdown menus, one for each day of the week (Monday to Sunday). Each day has two dropdowns: one for opening time and one for closing time. I used jQuery to populate all 14 dropdowns with a pre-defined list of ho ...

What is the best approach for managing JSON data and efficiently storing it for later retrieval?

I am currently working on a project using Rails 4.2 and Ruby 2.1.5. Imagine I have a textarea where users can input data in JSON format like this: { "City" : "Japan", "Population" : "20M" } What steps should I take to handle this JSON data so th ...

Would you like to learn how to set an auto-play video as the background in a webpage section, similar to the one found on http://www8.hp.com/in/en/home.html?

I was browsing the HP-India website and noticed they have a cool autoplay video in the background of a section below the header. I would love to recreate something similar on my own website. Any tips on how to achieve this? ...

When assigning JSON to a class object, the local functions within the class became damaged

This is a demonstration of Object Oriented Programming in JavaScript where we have a parent Class called Book with a child class named PriceDetails. export class Book { name: String; author: String; series: String; priceDetails: Array<Price> ...

The error message InvalidCharacterError is displayed when the attempt to create a new element using the 'createElement' method on the 'Document' object fails. This is due to the tag name provided ('/static/media/tab1.fab25bc3.png') not being a valid name

Hey everyone! I'm new to using React and I decided to try cloning Netflix by following a tutorial on YouTube. However, I've encountered an issue with rendering an image in a functional component. The error message I'm receiving is as follow ...

Having trouble with axios not transferring data to Express server in React (File upload)?

Hey there! I've encountered an issue with my React client and Express Server. When attempting to send data from the React client to the Express Server, it's not reaching its destination despite trying two different approaches. First Approach: U ...