0
Follow
4
View

Read a file and create array to loop through, javascript

cuiliang521 注册会员
2023-01-25 05:33

I would split the input into individual lines using regex:

str = str.split(/[\r\n]+/);
const header = str.shift().split(delimiter);

This also grabs the header line. Then map the data. Complete code:

const input = document.querySelector('input');
const fileReader = new FileReader();
fileReader.onload = (e) => {
    const data = csvToArray(e.target.result, ' ');
    console.log(data);
};

const csvToArray = (str, delimiter = ",") => {
    str = str.split(/[\r\n]+/);
    const header = str.shift().split(delimiter);
    return str.filter(line => line && line.includes(delimiter))
              .map(line => {
                  line = line.split(delimiter);
                  return {[header[0]]: line[0], [header[1]]: parseInt(line[1])};
              }
    );
};

input.onchange = (e) => {
    const [file] = e.target.files;
    fileReader.readAsText(file);
};

Output:

[{
  actions: "f",
  values: 4
}, {
  actions: "u",
  values: 2
}, {
  actions: "f",
  values: 8
}, {
  actions: "d",
  values: 1
}, {
  actions: "f",
  values: 2
}, {
  actions: "u",
  values: 3
}, {
  actions: "f",
  values: 3
}]

About the Author

Question Info

Publish Time
2023-01-25 05:33
Update Time
2023-01-25 05:33