繁体   English   中英

读取 CSV 文件并将名称写入一个数组并将值写入 Javascript 中的另一个数组

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM