I am a newbie programmer. I want to download json data from filtered json data that I have to CSV file. Here, my JSON API data:
The step should be like this:
- Pick date range from datepicker (example: 7May-8May)
- The filtered data will appear in inspect element using command console.log(filteredData)
- After that click the download button, and the filtered data (which is data from 7May-8May) will be downloaded.
I can do step 1 and step 2. But step 3 didn't work in my code. Anyone can help me with the code? Currently, this is my code: https://jsfiddle.net/estri012/2x3hmaLo/100/
$(function() {
$('input[name="datefilter"]').daterangepicker({
    showDropdowns : true,
autoUpdateInput: false,
locale: {
    cancelLabel: 'Clear'
}
});
$('input[name="datefilter"]').on('apply.daterangepicker', function(ev, picker) {
$(this).val(picker.startDate.format('YYYY-MM-DD') + ' - ' + picker.endDate.format('YYYY-MM-DD'));
var startDate = picker.startDate.format('YYYY-MM-DD');
var endDate = picker.endDate.format('YYYY-MM-DD');
if (startDate != '' && endDate != '') {
      console.log(startDate, endDate);
      var endpoint = 'https://gmlews.com/api/data/?node_id=1';
$.ajax({
method: "GET",
url: endpoint,
data: {
startDate: startDate,
endDate: endDate
},
success: function(data){
var data = data;
let filteredData = _.filter(data, function(data){ 
return (data.timestamp > startDate &&  
    data.timestamp < endDate)
});
console.log(filteredData);
} //function(data)end
}) //ajax end
} //if function end
$('input[name="datefilter"]').on('cancel.daterangepicker', function(ev, picker) {
$(this).val('');
});
}); //apply button end
//download button
$("#button1").on('click', function(e) {
// JSON to CSV Converter
    function ConvertToCSV(objArray) {
        var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
        var str = '';
        for (var i = 0; i < array.length; i++) {
            var line = '';
            for (var index in array[i]) {
                if (line != '') line += ','
                line += array[i][index];
            }
            str += line + '\r\n';
        }
        return str;
    }
    // Example
    $(document).ready(function () {
        // Create Object
        var filteredData = filteredData;
        // Convert Object to JSON
        var jsonObject = JSON.stringify(filteredData);
        // Convert JSON to CSV & Display CSV
        $('#button1').onclick(ConvertToCSV(jsonObject));
    });
})
}); //js function end
 
     
     
    