Last active
August 29, 2015 14:23
-
-
Save zachcr/d8f4d6306e76967b9279 to your computer and use it in GitHub Desktop.
JS CSV String Create Pro Function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function toCsvValue(theValue, sDelimiter) { | |
var t = typeof (theValue), output = ""; | |
if (typeof (sDelimiter) === "undefined" || sDelimiter === null) { | |
sDelimiter = '"'; | |
} | |
if (t === "undefined" || t === null) { | |
output = "" + ","; | |
} else if (t === "string") { | |
output = sDelimiter + theValue + sDelimiter + ","; | |
} else if (t == "object"){ | |
for(var val in theValue){ | |
output += toCsvValue(theValue[val], '"'); | |
} | |
} else { | |
output = String(theValue) + ","; | |
} | |
return output; | |
} | |
function toCsvName(obj, sDelimiter, cDelimiter, sub){ | |
var row = ""; | |
for (name in obj) { | |
if (obj.hasOwnProperty(name)) { | |
if(typeof obj[name] == "object"){ | |
row += toCsvName(obj[name], sDelimiter, cDelimiter, sub==""?name:sub+":"+name) | |
}else{ | |
row += [sDelimiter, sub==""?name:sub+":"+name, sDelimiter, cDelimiter].join(""); | |
} | |
} | |
} | |
return row | |
} | |
function toCsv(objArray, sDelimiter, cDelimiter) { | |
var i, l, name, value, obj, row, output = "", n, nl; | |
if (typeof (sDelimiter) === "undefined" || sDelimiter === null) { | |
sDelimiter = '"'; | |
} | |
if (typeof (cDelimiter) === "undefined" || cDelimiter === null) { | |
cDelimiter = ","; | |
} | |
for (i = 0, l = objArray.length; i < l; i += 1) { | |
obj = objArray[i]; | |
row = ""; | |
if(obj.hasOwnProperty("$$hashKey")){ | |
delete obj["$$hashKey"]; | |
} | |
if (i === 0) { | |
row = toCsvName(obj, sDelimiter, cDelimiter, "") | |
row = row.substring(0, row.length - 1); | |
output += row; | |
} | |
output += "\n"; | |
row = ""; | |
for (name in obj) { | |
value = obj[name]; | |
row += toCsvValue(value, '"'); | |
} | |
output += row; | |
output = output.substring(0, output.length - 1); | |
} | |
return output; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment