2016-06-10 67 views
0

正確的格式對象我有一個CSV文件:創建與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文件進行搜索,例如。

+2

轉問這個問題:http://stackoverflow.com/questions/7431268/how-to-read-data-from-csv-file-using-javascript – Oshadha

+1

就像大家說[在你以前的問題](http://stackoverflow.com/questions/37752811/extract-fields-from-object),對象不應該有重複的鍵。也許你想要一個對象數組。 'matrix = [{name:'Mike',number:'b1',level:0},{name:'Tom',number:'b2',level:0},...]'。您也可以考慮將名稱用作其他屬性的關鍵字(例如'matrix.Mike = {number:'b1',level:0}')。 –

+0

@MikeC:是的,你說得對。我喜歡你的想法。你能告訴我怎麼做?謝謝! – George

回答

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);
<pre></pre>

+0

:好的,很好!關於使用名稱作爲其他屬性的關鍵字(例如matrix.Mike = {number:'b1',level:0})? (upvoted) – George

+0

@George這不難推斷。你把'矩陣'作爲一個對象('var matrix = {}'),你做'矩陣[values [0]] = obj'。 'values [0]'是名字,所以你只需要添加一個新的屬性到'矩陣'來匹配這個名字。 –

+0

:好的,正確的。我怎樣才能使用類似'matrix.name'或'matrix.number'並給我結果? – George