0

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

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));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.