从csv创建具有适当格式的对象

时间:2016-06-10 19:06:22

标签: javascript

我有一个csv文件:

name,number,level
Mike,b1,0
Tom,b2,0
.....

我想构建类似的东西:

    matrix: { 

   { name: 'Mike', number: 'b1', level: 0 }, 
   { name: 'Tom', number: 'b2', level: 0 }, 
         ....
    }

我希望能够提取属性,例如matrix.name

我的问题是我想稍后使用ejs文件按名称搜索。

1 个答案:

答案 0 :(得分:1)

我假设您已经加载了CSV数据。如果没有,请you can refer to this question了解如何将数据加载到您的应用程序中。

从那里开始,我将假设您的数据存储在名为csv的变量中。您需要做的是首先处理该数据的每一行并在逗号上拆分值。在那之后,它就像创建一个新对象一样简单,每个值都将该对象添加到数组中。



var csv = 'name,number,level\n' +
          'Mike,b1,0\n' +
          'Tom,b2,0';

// Split the data into individual lines by splitting on the line break
var lines = csv.split('\n');

// I'm going to store the column names so I can use them to automatically get each value
// Note that I also removed the columns from the `lines` array so it won't be there when we go through it
var columns = lines.shift();

// Make sure we split on the commas
columns = columns.split(',');

// Create an array for us to store the objects in
var matrix = [];

// Next, we begin processing each line
for (var i = 0, len = lines.length; i < len; i++) {
  var line = lines[i];
  
  // Each value is separated by a comma. Split the line on those commas
  var values = line.split(',');
  
  // Now we create a new object that we'll store each value in
  var obj = {};
  
  // Remember that `columns` array? We're going to use that to generate our keys
  for (var j = 0, numOfColumns = columns.length; j < numOfColumns; j++) {
    // This is going to be 'name', 'number', and 'level'
    var column = columns[j];
    
    // Here is where we extract the matching value
    var value = values[j];
    
    // Now we add a new property to that new object using the `column` as the key
    // and the `value` as, well, the value
    obj[column] = value;
  }
  
  // The object has been generated, add it to the array
  matrix.push(obj);
}

// Display the complete array
document.querySelector('pre').innerText = JSON.stringify(matrix, null, 2);
&#13;
<pre></pre>
&#13;
&#13;
&#13;