美文网首页
读取csv文件的数据转化成Array

读取csv文件的数据转化成Array

作者: 扶得一人醉如苏沐晨 | 来源:发表于2023-05-25 19:34 被阅读0次

    读取到的csv文件内容如下

    name,age,sex
    张三,13,男
    李四,16,女
    王五,18,男
    赵六,20,女
    

    转化的结果如下

     [
            { name: "张三", age: "13", sex: "男" },
            { name: "李四", age: "16", sex: "女" },
            { name: "王五", age: "18", sex: "男" },
            { name: "赵六", age: "20", sex: "女" },
          ];
    

    方法如下

    function csvToArray(str, delimiter = ",") {
    
          // slice from start of text to the first \n index
          // use split to create an array from string by delimiter
          const headers = str.slice(0, str.indexOf("\n")).split(delimiter);
    
          // slice from \n index + 1 to the end of the text
          // use split to create an array of each csv value row
          const rows = str.slice(str.indexOf("\n") + 1).split("\n");
    
          // Map the rows
          // split values from each row into an array
          // use headers.reduce to create an object
          // object properties derived from headers:values
          // the object passed as an element of the array
          const arr = rows.map(function (row) {
            const values = row.split(delimiter);
            const el = headers.reduce(function (object, header, index) {
              object[header] = values[index];
              return object;
            }, {});
            return el;
          });
    
          // return the array
          return arr;
    }
    

    相关文章

      网友评论

          本文标题:读取csv文件的数据转化成Array

          本文链接:https://www.haomeiwen.com/subject/qsihedtx.html