Chuyển đến nội dung chính
eLearner.app
Mô-đun 8 · Bài học 2 trong tổng số 430/32 trong khóa học~15 min
Bài học theo mô-đun (2/4)

Thách thức: Trình phân tích cú pháp CSV

The CSV format (Comma-Separated Values) is everywhere: exports from Excel, database dumps, output from command-line tools. Parsing it is a small challenge that combines split, map, destructuring, and object construction.

The format

A minimal CSV is a multi-line string: the first row is the header (column names), then one row per record with fields separated by commas.

Code
nome,eta,citta
Alice,30,Roma
Bob,25,Milano

The classic goal is to turn it into an array of objects:

JS
[
  { nome: 'Alice', eta: '30', citta: 'Roma' },
  { nome: 'Bob', eta: '25', citta: 'Milano' },
];

The 3-step recipe

  1. Split the string by lines: csv.split('\n')
  2. Extract the header row: the first line, split by comma
  3. Map each remaining line to an object, pairing each field with the matching header
JS
function parseCSV(csv) {
  const righe = csv.split('\n');
  const intestazione = righe[0].split(',');
  return righe.slice(1).map((riga) => {
    const campi = riga.split(',');
    const record = {};
    intestazione.forEach((nome, i) => {
      record[nome] = campi[i];
    });
    return record;
  });
}

More modern alternatives:

JS
const record = Object.fromEntries(intestazione.map((nome, i) => [nome, campi[i]]));

Converting types

Parsed fields are always strings. If you know that some columns are numbers:

JS
record.eta = Number(record.eta);

Or write a small "schema":

JS
const numeriche = new Set(['eta', 'prezzo']);
intestazione.forEach((nome, i) => {
  const v = campi[i];
  record[nome] = numeriche.has(nome) ? Number(v) : v;
});

Try it

tập thể dục#js.m8.l2.e1
Nỗ lực: 0Đang tải…

Define `parseCSV(csv)` that takes a CSV string (first row = header, commas as separator). Return an array of objects with the header keys. All values stay as strings. Ignore empty rows.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

split on newline, first row = header, map over the rest, Object.fromEntries.

Giải pháp khả dụng sau 3 lần thử

Review exercise

tập thể dục#js.m8.l2.e2
Nỗ lực: 0Đang tải…

Define `columnMean(csv, columnName)` that parses the CSV, converts the column values to numbers, and returns their mean (a number). If there are no data rows return 0.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

Find the column index, map rows → Number, reduce to sum, divide by length.

Giải pháp khả dụng sau 3 lần thử