1 回答
TA贡献1812条经验 获得超5个赞
从分割线开始.split("\r\n"),然后添加对象shift()来弹出线,直到数组清空。代码片段生成以下数组:
[
{
"tag": "milk",
"date": "2020-10-25",
"quantity": "1"
},
{
"tag": "egg",
"date": "2020-10-04",
"quantity": "3"
},
{
"tag": "banana",
"date": "2020-10-03",
"quantity": "2"
},
{
"tag": "apple",
"date": "2020-10-10",
"quantity": "1"
},
{
"tag": "yoghurt",
"date": "2020-10-31",
"quantity": "5"
}
]
document.getElementById('inputfile').addEventListener('change', function() {
var fr = new FileReader();
fr.onload = function(e){
var res = [];
var lines = this.result.split("\r\n");
while(lines.length > 0){
res.push({
tag: getField(lines),
date: getField(lines),
quantity: getField(lines),
});
if(lines[0] == '*') lines.shift();
}
console.log(res);
}
fr.readAsText(this.files[0]);
})
function getField(lines){
return lines.shift().split(' = ')[1];
}
<input id="inputfile" type="file" value="upload" />
添加回答
举报