[英]Reading CSV file and writing names to one array and values to another in Javascript
在瀏覽了 Stack Overflow 的解決方案后,我一直不知道如何繼續。 我正在使用一個網站來構建一個 model 的東西,並且需要能夠讀取一個 CSV 文件,其布局如下所示:
Variable Name 1, Value 1
Variable Name 2, Value 2
Variable Name 3, Value 3
The main issue is that the website only supports Javascript and their own API linked below: https://insightmaker.com/sites/default/files/API/files/API-js.html
我嘗試編寫的代碼需要能夠將值放入兩個單獨的 arrays 或一個(如果需要),然后讀取變量名稱和值並進行更改。
如果不使用單獨的 JS 插件,這是否有可能?
任何幫助將不勝感激。
提前致謝
編輯:
到目前為止,我編寫的代碼如下所示:
// This function comes from the API that Insight Maker Provides
openFile({
read: "Text",
multiple: false,
onCompleted: function(result,allText){storeData(result,allText);}
});
// The Main function of the code
function storeData(result,allText){
alert(result.contents);
var name = [];
var value = [];
var txt = "";
var space = ",";
var newline = "\n";
//var reader = new FileReader();
}
到目前為止,我已經成功編寫的代碼管理到 output 的 CSV 文件的全部內容,該文件是從警告框中的對話框中選擇的。
我要做的是從 CSV 文件中獲取數據並將其放入數組中。
我正在嘗試編寫的代碼示例類似於此 c++ 代碼,並在 javascript 中找到此類代碼的替代品:
ifstream input("input.txt");
for (i = 0; i < 3; i++)
{
getline(input, text);
a[i] = text;
cout << text << endl;
}
這可以通過String.prototype.split()
、 String.prototype.match()
和Array.prototype.forEach()
輕松完成(如果.forEach
不可用,則可以使用一些等效的循環)。
// First, we have the string and we must split it on any newlines and semicolons.
// This can be done with a regex.
// Assuming csv holds the csv string.
var csvRows = csv.split(/;|\n/); // split on semicolons or newlines
// Now we create the arrays that will hold the name and values.
var varNames = [];
var varVals = [];
// Then iterate over all the csv rows, "row" is each split row
csvRows.forEach(row => {
// matches everything before the comma (variable name)
// then the comma (and an optional space)
// then finally everything after the comma (variable value)
var rowParts = row.match(/(.+),\s?(.+)/);
// push adds the element to the end of the array
// rowParts[0] is the whole match so rowParts[1] is the varName
varNames.push(rowParts[1]);
varVals.push(rowParts[2]);
});
這也可以是for (var i = 0; i < csvRows.length; i++)
但 forEach 更容易:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.