How to code a pure JS.
To transform CSV string:
col1,col2\na,b\nc,d
Into this object structure:
{"a":["a","b"],"c":["c","d"]...}
So it can br refered by eg.: Obj.c, to return:
["c","d"]
Try to turn: "col1,col2\na,b\nc,d";
into an array of array: [['a','b'],['c','d']];
Calling this: CSVToArray("col1,col2\na,b\nc,d",",", true);
const CSVToArray = (data, delimiter = ",", omitFirstRow = false) =>
data.slice(omitFirstRow ? data.indexOf("\n") + 1 : 0).split("\n").map(v => v.split(delimiter));
What about turn "col1,col2\na,b\nc,d"; into readable referral object structure (by first item on each line)?
var Obj = {
"a":["a","b"],
"c":["c","d"],
...
}
1 Answer 1
Use Object.fromEntries() to turn an array of [key, value] into an object with key: value properties.
const CSVToObject = (data, delimiter = ",", omitFirstRow = false) =>
Object.fromEntries(data.split("\n").slice(omitFirstRow ? 1 : 0).map(v => {
let fields = v.split(delimiter);
return [fields[0], fields];
}));
console.log(CSVToObject("col1,col2\na,b\nc,d", ",", true));
answered May 25, 2021 at 2:10
Barmar
789k57 gold badges555 silver badges669 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Explore related questions
See similar questions with these tags.
lang-js