[英]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.
我希望每个循环到 go 作为单独的行,然后转换为 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.您需要 append 在每个循环迭代中将所有项目(逗号分隔)转换为一个字符串并将其推送到您的
textarray
变量。
After the loop, join the textarray
with newline escape sequence (\n)在循环之后,使用换行符转义序列 (\n) 加入
textarray
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.您可以交替使用map并加入阵列原型。
After processing, you get the csv string处理后得到 csv 字符串
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"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.