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

2023-05-25  本文已影响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;
}
上一篇 下一篇

猜你喜欢

热点阅读