如何在 JavaScript 中将文本文件读入对象数组

我无法找到解决问题的最佳方法。我想将一个文本文件读入一个对象数组。数组的格式是固定的,但如果文本文件有更好的格式,那是可能的。


我目前拥有的文本文件具有以下结构:


item_tag = milk

item_date = 2020-10-25

item_quantity = 1

*

item_tag = egg

item_date = 2020-10-04

item_quantity = 3

*

item_tag = banana

item_date = 2020-10-03

item_quantity = 2

*

item_tag = apple

item_date = 2020-10-10

item_quantity = 1

*

item_tag = yoghurt

item_date = 2020-10-31

item_quantity = 5

*

每个对象都有三个属性,每个对象之间用 * 分隔。同样,我认为这是一种有用的格式,但我愿意接受建议。


我想把它变成一个结构如下的数组:


let Inventory = [

    {"item_name": "milk", "item_date": "2020-10-25", "item_quantity": 1},

    {"item_name": "egg", "item_date": "2020-10-04", "item_quantity": 3},

    {"item_name": "banana", "item_date": "2020-10-03", "item_quantity": 2},

    {"item_name": "apple", "item_date": "2020-10-10", "item_quantity": 1},

    {"item_name": "yoghurt", "item_date": "2020-10-31", "item_quantity": 5}

];

我见过其他类似的问题(例如thisthis),但这些不是针对对象数组的。这些解决方案也都使用 Node.JS,除非有必要,否则我宁愿不使用 Node。我已经看到了这个,其中使用了另一种没有 Node.js 的方法。我能够使用该线程中的这段代码显示文本:


document.getElementById('inputfile').addEventListener('change', function() { 

  

var fr = new FileReader(); 

fr.onload = function(){ 

    document.getElementById('output') 

            .textContent=fr.result; 

fr.readAsText(this.files[0]); 

}) 

如果可能,我如何修改它以将文本转换为对象数组?


谢谢你的帮助!


另外,是否也可以将数组(现已修改)转回文本文件?


UYOU
浏览 86回答 1
1回答

慕雪6442864

从分割线开始.split("\r\n"),然后添加对象shift()来弹出线,直到数组清空。代码片段生成以下数组:[&nbsp; {&nbsp; &nbsp; "tag": "milk",&nbsp; &nbsp; "date": "2020-10-25",&nbsp; &nbsp; "quantity": "1"&nbsp; },&nbsp; {&nbsp; &nbsp; "tag": "egg",&nbsp; &nbsp; "date": "2020-10-04",&nbsp; &nbsp; "quantity": "3"&nbsp; },&nbsp; {&nbsp; &nbsp; "tag": "banana",&nbsp; &nbsp; "date": "2020-10-03",&nbsp; &nbsp; "quantity": "2"&nbsp; },&nbsp; {&nbsp; &nbsp; "tag": "apple",&nbsp; &nbsp; "date": "2020-10-10",&nbsp; &nbsp; "quantity": "1"&nbsp; },&nbsp; {&nbsp; &nbsp; "tag": "yoghurt",&nbsp; &nbsp; "date": "2020-10-31",&nbsp; &nbsp; "quantity": "5"&nbsp; }]document.getElementById('inputfile').addEventListener('change', function() {&nbsp;&nbsp; var fr = new FileReader();&nbsp;&nbsp; fr.onload = function(e){&nbsp;&nbsp; &nbsp; var res = [];&nbsp;&nbsp; &nbsp; var lines = this.result.split("\r\n");&nbsp; &nbsp; while(lines.length > 0){&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; res.push({&nbsp; &nbsp; &nbsp; &nbsp; tag: getField(lines),&nbsp; &nbsp; &nbsp; &nbsp; date: getField(lines),&nbsp; &nbsp; &nbsp; &nbsp; quantity: getField(lines),&nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; if(lines[0] == '*') lines.shift();&nbsp; &nbsp; }&nbsp; &nbsp; console.log(res);&nbsp; }&nbsp;&nbsp; fr.readAsText(this.files[0]);&nbsp;})function getField(lines){&nbsp; return lines.shift().split(' = ')[1];}<input id="inputfile" type="file" value="upload" />
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript