I'm not good at javascript I've tried to search on stackoverflow.com but unable to find any help I'm trying to create CSV where I want to add content below relevant column heading/index, where the column heading/index is array key and column content is value, below is code but it is showing data only in two columns:
function downloadCSV(csvStr) {
CSV = ConvertToCSV(csvStr);
var uri = [
[
'application.csv','data:text/csv;charset=utf-8,' escape(CSV)
]];
downloadAll(uri)
}
function ConvertToCSV(objArray) {
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
let str = "";
for (var i = 0; i < array.length; i ) {
var line = '';
for (var index in array[i]) {
if (line != '') line = ''
line = `${index} ,`
line = `${array[i][index]}`
}
str = line '\n';
}
return str;
}
And below is the array data I have where I want to use First, Street Address as the column heading
0: {First: 'asdkjf,\n', Street Address: 'lasdkfj ,\n', City:
'alsdf,\n', State: 'Alaska,\n', ZIP / Postal Code: 'asl;dfj,\n', …}
1: {First: 'asdkjf,\n', Street Address: 'lasdkfj ,\n', City: 'alsdf,\n', State: 'Alaska,\n', ZIP / Postal Code: 'asl;dfj,\n', …}
This is how I'm getting the result
CodePudding user response:
Consider the following example. This assumes you are receiving JSON Data format.
var myDataArray = [{
"First": "asdkjf",
"Street Address": "lasdkfj",
"City": "alsdf",
"State": "Alaska",
"ZIP / Postal Code": "asl;dfj"
}, {
"First": "asdkjf",
"Street Address": "lasdkfj",
"City": "alsdf",
"State": "Alaska",
"ZIP / Postal Code": "asl;dfj"
}];
function convertToCSV(jsonData) {
var rows = [];
jsonData.forEach(function(obj, i) {
var keys = Object.keys(obj);
keys.forEach(function(key, j) {
rows.push(['"' key '"', '"' obj[key] '"'].join(","));
});
rows.push('\r\n');
});
return rows.join("\r\n");
}
console.log(convertToCSV(myDataArray));
You can make use of many of the Array tools. This helps create the comma separation. arr.join(",")
will result in a String of each element of the array, joined by a ,
.
This results in the following:
"First","asdkjf"\r\n
"Street Address","lasdkfj"\r\n
"City","alsdf"\r\n
"State","Alaska"\r\n
"ZIP / Postal Code","asl;dfj"\r\n
\r\n
"First","asdkjf"\r\n
"Street Address","lasdkfj"\r\n
"City","alsdf"\r\n
"State","Alaska"\r\b
"ZIP / Postal Code","asl;dfj"\r\n
\r\n
CSV Format is generally:
Cell1,Cell2,Cell3\r\n
Cell4,Cell5,Cell6\r\n
Where each line is terminated with a Carriage Return (\r
) and New Line (\n
) character at the End of Line. Some Operating systems do not use the Carriage Return. If this is a Windows format, you will want to use both. More complex CSV content may need to quoted, enclosed within double-quote characters.
See More:
- https://en.wikipedia.org/wiki/Comma-separated_values
- https://datatracker.ietf.org/doc/html/rfc4180#page-1
CodePudding user response:
Posting here because may be someone need it. I made some changes to the answer given by @Twisty because it was again creating only two columns where column one was heading( array key ) and two was content( array value ) what I needed was to add all headings ( array keys ) to top row and content ( array value ) to relevant box. I know it's less efficient because I used three loops but it was the only choice to me so far! Here is the code below:
function ConvertToCSV(objArray) {
var jsonData = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var rows = [];
let inc = 1;
jsonData.forEach(function(obj, i) {
var keys = Object.keys(obj);
let keyInc = 1;
if(inc === 1){
keys.forEach(function(key, j) {
if(keyInc === 1){
rows.push([',"' key '"'].join(","));
}else{
rows.push(['"' key '"'].join(","));
}
keyInc
});
rows.push('\n\n');
}
keys.forEach(function(key, j) {
if(obj[key].includes('"')){
let doubleQuoteValue = obj[key].replaceAll('"', '');
rows.push(['"' doubleQuoteValue '"'].join(","));
console.log('double quote',doubleQuoteValue);
}else{
rows.push(['"' obj[key] '"'].join(","));
}
console.log(obj[key]);
keyInc
});
inc ;
rows.push('\n');
});
return rows;
}