LoginSignup
0
1

More than 1 year has passed since last update.

JSでCSV操作

Posted at

JavaScriptで

CSVをDTOに

csv→dto.js
  // CSVをDTOのListに直す
  let csvToDto = (csv) => {
    let rows = csv.split("\r\n");
    let header = rows[0].split(",");
    let records = [];
    for (let i = 1; i < rows.length; i++) {
      let row = {};
      rows[i].split(",").forEach((val, index) => {
        row[header[index]] = val;
      });
      records[i - 1] = row;
    }
    return records;
  };

DTOをCSVに

dto→csv.js
  // DTOのListをCSVに直す
  let dtoToCsv = (list) => {
    console.log(list);
    let csv = Object.keys(list[0]).join(",") + "\r\n";
    list.forEach((dto) => {
      csv += Object.values(dto).join(",") + "\r\n";
    });
    return csv;
  };
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1