简体   繁体   English

从多个 CSV 文件数据创建一个新数组 arrays

[英]Create a new array of arrays from multiple CSV files data

I'm creating a React app in which I want to upload multiple CSV files and create an array out of them.我正在创建一个 React 应用程序,我想在其中上传多个 CSV 文件并从中创建一个数组。 I want them to be in the below format.我希望它们采用以下格式。

Currently, I see the output as:目前,我看到 output 为:

[
 {"Name":"user 1","Age":"12","Rank":"2"},
 {"Name":"user 2","Age":"13","Rank":"3"},
 {"Name":"user 3","Age":"10","Rank":"2"},
 {"Name":"user 4","Age":"16","Rank":"1"},
 {"Name":"user 5","Age":"14","Rank":"5"},
 {"Name":"user 6","Age":"11","Rank":""}
]

and

[
 {"Name":"Person 1","Age":"27","Rank":"6"}, 
 {"Name":"Person 2","Age":"32","Rank":"3"},
 {"Name":"Person 3","Age":"25","Rank":"2"},
 {"Name":"Person 4","Age":"31","Rank":"4"},
 {"Name":"Person 5","Age":"22","Rank":"1"},
 {"Name":"Person 6","Age":"29","Rank":""}
]

But I want the output as但我想要 output 作为

[
 [
  {"Name":"user 1","Age":"12","Rank":"2"},
  {"Name":"user 2","Age":"13","Rank":"3"},
  {"Name":"user 3","Age":"10","Rank":"2"},
  {"Name":"user 4","Age":"16","Rank":"1"},
  {"Name":"user 5","Age":"14","Rank":"5"},
  {"Name":"user 6","Age":"11","Rank":""}
 ], 
 [
  {"Name":"Person 1","Age":"27","Rank":"6"},
  {"Name":"Person 2","Age":"32","Rank":"3"},
  {"Name":"Person 3","Age":"25","Rank":"2"},
  {"Name":"Person 4","Age":"31","Rank":"4"},
  {"Name":"Person 5","Age":"22","Rank":"1"},
  {"Name":"Person 6","Age":"29","Rank":""}
 ]
]

File1:文件一:

Name,Age,Rank
user 1,12,2
user 2,13,3
user 3,10,2
user 4,16,1
user 5,14,5
user 6,11,7

File2:文件2:

Name,Age,Rank
Person 1,27,6
Person 2,32,3
Person 3,25,2
Person 4,31,4
Person 5,22,1
Person 6,29,5

Here is my code.这是我的代码。

    import { useState } from "react";
    const LoadFiles = () => {
      const [files, setFiles] = useState([]);
      const [processData, setProcessData] = useState(false);
      const [allData, setAllData] = useState([]);
    
      const processCSV =   (str, delim = ",") => {
        const headers = str.slice(0, str.indexOf("\n")).split(delim);
        const rows = str.slice(str.indexOf("\n") + 1, str.length - 1).split("\n");
        let nArray = rows.map((row) => {
          const values = row.split(delim);
          const eachObj = headers.reduce((obj, header, i) => {
            obj[header] = values[i];
            return obj;
          }, {});
          return eachObj;
        });
        setAllData([...allData, { nArray }]);
      };
    
      const handleUpload =   () => {
        Array.from(files).forEach(async (file) => {
          const currFile = file;
          const reader = new FileReader();
          reader.onload = (e) => {
            const text = e.target.result;
            processCSV(text);
          };
          reader.readAsText(currFile);
        });
        setProcessData(true);
      };
    
      const handleChange =   (e) => {
        e.preventDefault();
        setFiles(e.target.files);
      };
    
      return (
        <div id="formWrapper">
          <form id="csv-form">
            <input
              type="file"
              accept=".csv"
              id="csvFile"
              multiple
              onChange={(e) => handleChange(e)}
            />
            <button
              onClick={(e) => {
                e.preventDefault();
                handleUpload();
              }}
            >
              Upload your csv
            </button>
          </form>
    
          {processData && console.log(allData)}
        </div>
      );
    };
    
    export default LoadFiles;

Here allData should hold my final array.这里allData应该保存我的最终数组。 Where am I going wrong and how can I fix this?我哪里出错了,我该如何解决?

Here is a working codesandbox .这是一个工作codesandbox

As per conversation in the comments, it appears the problem was with below line:根据评论中的对话,问题似乎出在以下行:

setAllData([...allData, { nArray }]);

A new codesandbox forked which changed the line like this:一个新的 codesandbox forked 改变了这样的行:

setAllData(prev => ([...prev, nArray]));

(and made few other changes) seems to have fixed the issue faced. (并进行了一些其他更改)似乎已经解决了所面临的问题。

It is also pertinent to note that useEffect may be simple way to console.log a state variable.还需要注意的是, useEffect可能是console.log state 变量的简单方法。 For example, if the state variable we need to log is allData (in the above example), then below may be suitable例如,如果我们需要记录的 state 变量是allData (在上面的例子中),那么下面可能是合适的

useEffect(
  () => console.log(allData),
  [allData]
);

This may be explained like so:这可以这样解释:

  • Whenever allData changes (noted in the dependency array of the useEffect )每当allData发生变化时(在useEffect的依赖数组中注明)
  • Execute the console.log (the call-back of useEffect )执行console.loguseEffect的回调)

Codesandbox Link with issues fixed: https://codesandbox.io/s/gifted-cerf-to55i9已修复问题的Codesandbox链接https://codesandbox.io/s/gifted-cerf-to55i9

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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