I have a set of JSON format as below. During converting from JSON to CSV, the function is worked but not all key
is exist in the CSV file. How to allow all the key
available in the CSV file?
Reference: How to convert JSON to CSV format and store in a variable
JSON
var data = {
"items": [
{
"bandwidth": "",
"destination_ipv4": "",
"destination_ipv6": ""
},
{
"interface": "",
"vlan": null,
"service": ""
},
{
"ipv4_address": "",
"ipv6_address": ""
},
{
"vrf": ""
}
]
};
JS
function download_file(data) {
const items = data.items
const replacer = (key, value) => value === null ? '' : value
const header = Object.keys(items[0])
let csv = items.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','))
csv.unshift(header.join(','))
csv = csv.join('rn')
var link = document.createElement("a");
link.id="lnkDwnldLnk";
document.body.appendChild(link);
blob = new Blob([csv], { type: 'text/csv' });
var csvUrl = window.webkitURL.createObjectURL(blob);
var filename = 'Result.csv';
jQuery("#lnkDwnldLnk")
.attr({
'download': filename,
'href': csvUrl
});
jQuery('#lnkDwnldLnk')[0].click();
document.body.removeChild(link);
}
3
Answers
In the provided JavaScript code, the header variable is used to store the keys of the first object in the items array. This means that only the keys of the first object will be used as the header in the CSV file. To include all the keys from all the objects in the CSV file, you can modify the code as follows:
This modified code uses the reduce method to iterate over each object in the items array and collect all the unique keys. It then uses these keys to create the header row in the CSV file.
With this modification, all the keys from all the objects in the items array will be included in the CSV file.
Instead of just using the first element in
data.items
you will need to get all keys from all elements in the array.You can do this using
Array.prototype.flatMap
You should use this instead of
const header = Object.keys(items[0]);
Here is my version