I'm attempting to create one single string from an array of arrays, but with one condition, the last 2 elements (doesn't apply to first row)from the array need to be in "".
The array looks like this:
const data = [
//( not applied to this row)
[
"id",
"group_name",
"admin",
"email_",
"og.id",
"created_by.email",
"students",
"namesids"
],
//( applied to the following rows)
[
"80",
"Test group",
"nilton.updated",
"[email protected]",
"22",
"[email protected]",
"[email protected],[email protected]",
"13,14,27"
],
[
"18",
"PRO Group",
"",
"",
"22",
"[email protected]",
"",
"13000"
],
[
"10",
"Test Group",
"TEst",
"[email protected]",
"22",
"[email protected]",
"",
""
]
]
Details:
The data that doesn't contain nothing need to be in quotes too. What I expect, and what I attempted until now:
expected (this is one string, last char from each line is \n):
const this_is_a_string = "
id,group_name,admin,email_,og.id,created_by.email,students,namesids
80,Test group,nilton.updated,[email protected],22,[email protected],"[email protected],[email protected]","13,14,27"
10,Test Group,TEst,[email protected],22,[email protected],"",""
...
"
What I attempted, didn't the the right answer:
data.map(objects => {
const newAr = objects.reduce((arr, values, i) => {
arr = arr ',' values
if (i === 6 || i ===7) return arr = arr ',' '"' values '"';
return arr;
}, "")
console.log(newAr.substring(1));
return;
})
If possible to create a function that is able to receive the data
as first param and an array of position that need to be in quotes. The arrays will always have the same size as the first one, that why I know the positions that need to be in quotes.
CodePudding user response:
For each row, use Array.prototype.slice() to separate the last two elements from the rest.
Then it's a matter of mapping those last two entries to quoted values and joining everything back up, separated by commas.
Each row can then be joined into a single string separated by newlines.
const data = [["id","group_name","admin","email_","og.id","created_by.email","students","namesids"],["80","Test group","nilton.updated","[email protected]","22","[email protected]","[email protected],[email protected]","13,14,27"],["18","PRO Group","","","22","[email protected]","","13000"],["10","Test Group","TEst","[email protected]","22","[email protected]","",""]];
const rowMapper = (row) =>
[...row.slice(0, -2), ...row.slice(-2).map((v) => `"${v}"`)].join(",");
const [header, ...rows] = data;
const csv = [header.join(","), ...rows.map(rowMapper)].join("\n");
console.log(csv);
As mentioned in the comments, you might as well quote every value, even the headers and escape any embedded quotes
const csv = data
.map((row) => row.map((v) => `"${v.replace(/"/g, '""')}"`).join(","))
.join("\n");