How To Approach Parsing Csv In Javascript
(My first post, I apologise for any mistakes) I'm working with a small set of data in CSV files, which I need to read, process, and then export as a text file. The format of the CS
Solution 1:
My advice would be to split the work flow in to three steps:
- Parse all rows to javascript objects
- Perform the logic on the array of objects
- Stringify the objects back to CSV
// This creates an object based on an order of columns:constEntry = ([rego, status, shift, location, loaded]) =>
({ rego, status, shift, location, loaded });
// Which entries are we interested in?constshouldHandleEntry = ({ loaded }) => loaded === "1";
// How do we update those entries?constupdateEntry = entry => ({
...entry,
shift: ["CCA4118"].includes(entry.rego)
? "5:33"
: entry.shift
});
// What do we export?constexportEntry = ({ rego, shift }) => `${rego},${shift}`;
// Chain the steps to create a new table:console.log(
csvBody(getCSV())
.map(Entry)
.filter(shouldHandleEntry)
.map(updateEntry)
.map(exportEntry)
.join("\n")
)
// (This needs work if you're using it for production code)functioncsvBody(csvString) {
return csvString
.split("\n")
.map(line => line.trim().split(","))
.slice(1);
};
functiongetCSV() { return`REGO,STATUS,SHIFT,LOCATION,LOADED
CCA4110,StatusON,5:43,Brisbane,1
CCA4112,StatusON,5:44,Sydney,0
CCA4118,StatusON,6:11,Melbourne,1`; }
Post a Comment for "How To Approach Parsing Csv In Javascript"