I want to read csv file as objects array using javascript & React

나의 재물운? 연애운은?

AI가 봐주는 내 사주팔자 - 운세박사

https://aifortunedoctor.com/

I want to read csv file as objects array using javascript & React

영리치 0 967 2023.02.08 13:52

You can read a CSV file in JavaScript and convert it into an array of objects using the fetch API or any other HTTP client library. Here's an example using fetch:


fetch('file.csv')

  .then(response => response.text())

  .then(text => {

    let rows = text.split('\n');

    let header = rows[0].split(',');

    let data = [];

    for (let i = 1; i < rows.length; i++) {

      let obj = {};

      let currentRow = rows[i].split(',');

      for (let j = 0; j < header.length; j++) {

        obj[header[j]] = currentRow[j];

      }

      data.push(obj);

    }

    console.log(data);

  });



If you're using a different HTTP client library, the process would be similar, but the syntax may differ. In React, you can store the data in the component state and display it in the UI using the map function.



I want to read csv file as objects array using javascript & React. If a row has a value wrapped "", I want to regard the value as a one even though the value has comma (,). For example, there is a value that "[127.064021,37.5435591]", I want to regard that value as a object whose column is [127.064021,37.5435591]


You can modify the previous code to handle the case where a value is wrapped in double quotes:


fetch('file.csv')

  .then(response => response.text())

  .then(text => {

    let rows = text.split('\n');

    let header = rows[0].split(',');

    let data = [];

    for (let i = 1; i < rows.length; i++) {

      let obj = {};

      let currentRow = rows[i].split(',');

      for (let j = 0; j < header.length; j++) {

        let value = currentRow[j];

        if (value[0] === '"' && value[value.length - 1] === '"') {

          value = value.slice(1, -1);

        }

        obj[header[j]] = value;

      }

      data.push(obj);

    }

    console.log(data);

  });



In this code, the if statement checks if the first and last characters of the current value are double quotes. If they are, the double quotes are removed by using the slice method. The resulting value is then stored in the object with the corresponding header key.

Comments

나의 재물운? 연애운은?

AI가 봐주는 내 사주팔자 - 운세박사

https://aifortunedoctor.com/

Category
Magazine
훈남/훈녀
 
 
 
상점
Facebook Twitter GooglePlus KakaoStory NaverBand