简体   繁体   中英

Javascript: How to loop through data object and create a comma separated file

I want to create a comma separated file with a few input strings I have and wonder if there is an easier way to do this. My inputs are a combination of variables and data objects.

  var textarray = [];
  for(var i = 0; i<data.length; i++){ //data is my object
    var sms = ('#TxtMessage').val();
    var date = ('#datetxt').val()
    var code = ('#code').val()
    var type = data[i].producttype;
    var mixer = data[i].mixer;
    var quality = data[i].quality;
    textarray.push();
  }

But its going in as a continous list of strings. I want each loop to go as a separate line and then convert to csv. I am trying to put it in an array and then convert to text but if we can do it directly I would take that

You need to append all of the items, comma separated, to a string in each loop iteration and push it to your textarray variable.

After the loop, join the textarray with newline escape sequence (\n)

 var textarray = []; var getRandValue = () => { var fakeValues = ['Lorem', 'Ipsum', 'Dolar', 'Sit', 'Amet', 'Bla', 'bla'] return fakeValues[Math.floor(Math.random() * fakeValues.length)] } for(var i = 0; i < 10; i++){ //data is my object var sms = getRandValue() var date = getRandValue() var code = getRandValue() var type = getRandValue() var mixer = getRandValue() var quality = getRandValue() var csvLine = `${sms}, ${date}, ${code}, ${type}, ${mixer}, ${quality}` textarray.push(csvLine) } var resultCSV = textarray.join('\n') var output = document.getElementById('output') output.innerText = resultCSV
 <div id="output"></div>

You can alternately use the map and join of the array prototype.

After processing, you get the csv string

 const data = [{ producttype: 'type1', mixer: 'mixer1', quality: 'quality1' },{ producttype: 'type2', mixer: 'mixer2', quality: 'quality2' },{ producttype: 'type3', mixer: 'mixer3', quality: 'quality3' }]; const sms = $('#TxtMessage').val(); const date = $('#datetxt').val() const code = $('#code').val(); const csvStr = data.map(m => [sms, date, code, m.producttype, m.mixer, m.quality].join(',')).join('\r\n'); console.log(csvStr);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="hidden" id="TxtMessage" value="TxtMessage"/> <input type="hidden" id="datetxt" value="datetxt"/> <input type="hidden" id="code" value="code"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM