Skip to content

Instantly share code, notes, and snippets.

@guibranco
Created April 8, 2020 19:54
Show Gist options
  • Save guibranco/4b5154cf1daf96206e756ba6f0c74414 to your computer and use it in GitHub Desktop.
Save guibranco/4b5154cf1daf96206e756ba6f0c74414 to your computer and use it in GitHub Desktop.
Função para ler um CSV com um separador qualquer - Desenvolvimento Web - Facebook - https://www.facebook.com/groups/desenvolvimentoweb/permalink/3055949921130093
function parseCSV(data, separator) {
const lines = data.split(/\r\n|\n/);
const header = lines[0].split(separator);
const result = [];
for(let i = 1; i < lines.length; i++){
const fields = lines[i].split(separator);
const line = {};
for(let k = 0; k < header.length; k++)
line[header[k]] = fields[k];
result.push(line);
}
return result;
}
/*
var data = "a;b;c;d;e;f;\r\n1;2;3;4;5;6;\r\n1;2;5;6;7;8;\r\n0;;1;;2;;3;";
var result = parseCSV(data,";");
console.log(result);
Result should be an array with 3 items, each item is a named object:
0: {a: "1", b: "2", c: "3", d: "4", e: "5", …}
1: {a: "1", b: "2", c: "5", d: "6", e: "7", …}
2: {a: "0", b: "", c: "1", d: "", e: "2", …}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment