在javascript中加载和处理csv文件

问题描述 投票:0回答:1

我正在尝试在

csv
中加载
javascript
文件并根据其中的值对其进行过滤。我的
csv
文件是使用以下
r
脚本创建的:

d <- structure(list(U = c("a", "b", "c", "d", "e", "f"), 
                    T = c(1, 2, 3, 4, 5, 6), 
                    aE = c("X", "Y", "Y", "Y", "Y", "Y"), 
                    aA = c("R", "S", "S", "T", "U", "V"), 
                    aX = c("P", "Q", "Q", "W", "P", "P"), 
                    aP = c("Z", "A", "A", "A", "Z", "A"), 
                    aJ = c("K", "L", "L", "K", "K", "L"), 
                    aD = c("C", "B", "B", "B", "D", "D"), 
                    bE = c("X", "Y", "Y", "X", "X", "Y"), 
                    bA = c("G", "R", "R", "I", "I", "T"), 
                    bX = c("M", "N", "N", "O", "M", "O"), 
                    bP = c("Z", "A", "A", "Z", "A", "Z"), 
                    bJ = c("K", "L", "L", "L", "K", "L"), 
                    bD = c("B", "C", "C", "C", "B", "C")), 
               row.names = c(NA, -6L), 
               class = c("tbl_df", "tbl", "data.frame"))

write.csv(d, "data.csv")

csv 文件如下所示:

image1

编辑

文本编辑器中的 csv 文件如下:

"","U","T","aE","aA","aX","aP","aJ","aD","bE","bA","bX","bP","bJ","bD"
"1","a",1,"X","R","P","Z","K","C","X","G","M","Z","K","B"
"2","b",2,"Y","S","Q","A","L","B","Y","R","N","A","L","C"
"3","c",3,"Y","S","Q","A","L","B","Y","R","N","A","L","C"
"4","d",4,"Y","T","W","A","K","B","X","I","O","Z","L","C"
"5","e",5,"Y","U","P","Z","K","D","X","I","M","A","K","B"
"6","f",6,"Y","V","P","A","L","D","Y","T","O","Z","L","C"

然后我将其加载到 JavaScript 中并尝试使用以下代码处理它:

$(document).ready(function() {
    var task = '1';
    var userID = 'a';

    fetch('https://raw.githubusercontent.com/username/repo/main/data.csv')
        .then(response => response.text())
        .then(csvData => {
            // Parse CSV data into an array of rows
            var rows = csvData.trim().split('\n');

            // Extract headers and trim whitespace
            var headers = rows[0].split(',').map(header => header.trim());

            // Extract and parse each row (excluding headers)
            var data = rows.slice(1).map(row => {
                var rowValues = row.split(',').map(value => value.trim());
                var rowData = {};

                headers.forEach((header, index) => {
                    rowData[header] = rowValues[index];
                });

                return rowData;
            });

            console.log('Parsed Data:', data);

            // Filter data to only include rows that match the specified task and userID
            var filteredData = data.filter(row => row['T'] === task && row['U'] === userID);

            console.log('Filtered Data:', filteredData);

            // Display the filtered row in the HTML document
            if (filteredData.length > 0) {
                var resultRow = filteredData[0]; // Get the first (and only) matching row
                displayResultRow(resultRow); // Call function to display the row in the document
            } else {
                console.log('No matching row found.');
                // Handle case where no matching row is found
            }

            return filteredData; // Return the filtered array of data objects
        })
        .then(filteredData => {
            console.log('Returned Filtered Data:', filteredData);
            // Use the returned filtered array of data objects here or perform additional actions
        })
        .catch(error => {
            console.error('Error fetching or processing CSV:', error);
            // Handle fetch or processing errors
        });

    function displayResultRow(row) {
        // Assuming there is a container in your HTML document with id="resultContainer"
        var resultContainer = document.getElementById('resultContainer');
        
        // Clear previous content
        resultContainer.innerHTML = '';

        // Create and append elements to display the row data
        Object.keys(row).forEach(key => {
            var rowElement = document.createElement('div');
            rowElement.textContent = `${key}: ${row[key]}`;
            resultContainer.appendChild(rowElement);
        });
    }
});

初始数据加载有效,因为我能够成功看到数据对象。然而,没有一个处理成功。我相信这是因为列和行可能无法正确创建。这是数据对象在我的 js 代码编辑器中的样子:

Parsed Data:
(6) [{...}, {...}, {...}, {...}, {...}, ...]
0
:
(15) {"": ""1"", "U": ""1...}
1
:
(15) {"": ""2"", "U": ""2...}
2
:
(15) {"": ""3"", "U": ""3...}
3
:
(15) {"": ""4"", "U": ""4...}
4
:
(15) {"": ""5"", "U": ""5...}
5
:
(15) {"": ""6"", "U": ""6...}

在我看来,这就像正在读入行号,并且列标题被视为某种其他值。无论如何,数据过滤不起作用。我也不确定如何存储数据对象来访问它。

如何获取已成功加载到

csv
中的
javascript
文件,对其进行处理以选择具有
U
= 上面指定的 userID 且
T
= 上面指定任务的唯一行?如何将此行存储为对象(例如,标题为
info_object
),以便我可以提取该行中特定列的特定值(例如:将 aE 的值保存为对象“info_aE”)?

javascript arrays csv sorting
1个回答
0
投票

您确实不需要编写自己的 CSV 解析器。看看这个快速且易于使用的库

csv-parse

https://www.npmjs.com/package/csv-parse

虽然它可用并且经常与 NodeJS 后端一起使用,但它附带了适合在浏览器中使用的 ESM 发行版,如下所述:

https://csv.js.org/parse/distributions/browser_esm/

© www.soinside.com 2019 - 2024. All rights reserved.