Need help to convert a CSV string into an array of array of objects. Struggling with handling \n
in the incoming request, causing issues with splitting and code errors. The string format includes messages enclosed in "
.
"id,urn,title,body,risk,s.0.id,s.1.id,s.2.id,a.0.id,a.1.id,a.2.id,a.3.id
302,25,\"Secure Data\",\"Banking can save a lot of time but it’s not without risks...
Attempting to organize this content from CSV string into an array for better manipulation. Here is the initial approach:
function csv_To_Array(str, delimiter = ",") {
const header_cols = str.slice(0, str.indexOf("\n")).split(delimiter);
const row_data = str.slice(str.indexOf("\n") + 1).split("\n");
const arr = row_data.map(function (row) {
const values = row.split(delimiter);
const el = header_cols.reduce(function (object, header, index) {
object[header] = values[index];
return object;
}, {});
return el;
});
// return the array
return arr;
}
Considering using regex to handle splitting based on commas or \n characters, taking care if there are additional " symbols within the text:
array.split(/,/\n(?!\d)/))