Function to parse a Javascript object and return a CSV
Description

It would appear that your current solution is a bit complicated. Using JSON.parse just to ensure that you escape , is overkill.

The overall solution can be drastically simplified as you will see in this post.

const before let and let before var

All variables should be declared by default with const. If a variable is going to be mutated then use let. Don't use var unless that is what you intended.

/// bad
var dataFromAPI = ...


/// good
const dataFromAPI = ...


note: pushing an element to a list will only mutate the array and not the variable, thus no error



Work with arrays and not with strings.

/// bad
csvOutput = "Index,Field Value\n";


/// good
const csvOutput = [
  ["Index", "Field", "Value"]
];




Function names should describe what they do.

The convertToCSVandDownload method only converts to CSV but doesn't download. Change the name to convertToCSV



Working Solution

Use Array#reduce, destructuring assignment, Array#map, Array#join and spread syntax



const dataFromAPI = [{"name":"first"},{"name":"sec,ond"},{"name":"third 'jibberish"},{"name":"fourth, jibberish"}]

function convertToCSV(data, headers) {
  return data
  .reduce((a,{name},i)=&gt;[...a, [i, `"${name}"`]], [headers])
  .map(row=&gt;row.join(","))
  .join("\n");
}

const res = convertToCSV(dataFromAPI, ["Index", "Field Value"]);

console.log(res)