javascript - create object with proper format from csv -
i have csv file :
name,number,level mike,b1,0 tom,b2,0 .....
i want construct like:
matrix: { { name: 'mike', number: 'b1', level: 0 }, { name: 'tom', number: 'b2', level: 0 }, .... }
and want able extract properties,for example matrix.name
.
my problem want search later using ejs file name example.
i'm going assume have csv data loaded. if not, you can refer question on how load data application.
going there, i'm going assume data stored in variable called csv
. need first process each line of data , split values on commas. after that, it's simple creating new object each value , adding object array.
var csv = 'name,number,level\n' + 'mike,b1,0\n' + 'tom,b2,0'; // split data individual lines splitting on line break var lines = csv.split('\n'); // i'm going store column names can use them automatically each value // note removed columns `lines` array won't there when go through var columns = lines.shift(); // make sure split on commas columns = columns.split(','); // create array store objects in var matrix = []; // next, begin processing each line (var = 0, len = lines.length; < len; i++) { var line = lines[i]; // each value separated comma. split line on commas var values = line.split(','); // create new object we'll store each value in var obj = {}; // remember `columns` array? we're going use generate our keys (var j = 0, numofcolumns = columns.length; j < numofcolumns; j++) { // going 'name', 'number', , 'level' var column = columns[j]; // here extract matching value var value = values[j]; // add new property new object using `column` key // , `value` as, well, value obj[column] = value; } // object has been generated, add array matrix.push(obj); } // display complete array document.queryselector('pre').innertext = json.stringify(matrix, null, 2);
<pre></pre>
Comments
Post a Comment