Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add header to object or csv string

I'm using Papaparse with my csv (no header) string to give me an array of objects. I can parse the string without a header then change the keys or I can add a header string to my csv string and then parse that. I haven't had luck with either approach

var csvString = txtArea.value.trim();
var header = 'Header1,Header2,Header3,Header4';
csvString = header+csvString;
var objects = Papa.parse(csvString,{header:true});
like image 979
Bum Son Avatar asked Oct 31 '22 15:10

Bum Son


1 Answers

You must insert a linebreak \n between header and the CSV :

csvString = header+'\n'+csvString;

Then your code works and produces objects on the form

{ 
   "Header1" : "a",
   "Header2" : "b",
   ..
}

demo -> http://jsfiddle.net/rf1h0h10/

like image 147
davidkonrad Avatar answered Nov 09 '22 05:11

davidkonrad