Function to parse a Javascript object and return a CSV This function converts a Javascript Object into a CSV.



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

function convertToCSVandDownload(objArray) {
    var csvOutput = "";
    Object.keys(objArray).forEach(function(key) {
      if (csvOutput.length == 0) {
        csvOutput = "Index,Field Value\n";
        csvOutput = csvOutput + JSON.stringify(key) + "," + JSON.stringify(objArray[key]["name"]) + "\n";         
      } else {
        csvOutput = csvOutput + JSON.stringify(key) + "," + JSON.stringify(objArray[key]["name"]) + "\n";                 
      }
    })
    return csvOutput;
}

console.log(convertToCSVandDownload(dataFromAPI));
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)