【问题标题】:How to read a text file into an array of objects in JavaScript如何将文本文件读入 JavaScript 中的对象数组
【发布时间】:2021-01-19 18:39:12
【问题描述】:

我很难找到解决问题的最佳方法。我想将文本文件读入对象数组。数组的格式是固定的,但是如果有文本文件的格式会更好,那就可以了。

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

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。我见过this,在没有Node 的情况下使用了另一种方法。我可以使用该线程中的此代码显示文本:

document.getElementById('inputfile').addEventListener('change', function() { 
  
var fr = new FileReader(); 
fr.onload = function(){ 
    document.getElementById('output') 
            .textContent=fr.result; 
} 
fr.readAsText(this.files[0]); 
}) 

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

感谢您的帮助!

顺便说一句,是否也可以将数组(现在已修改)转回文本文件?

【问题讨论】:

    标签: javascript arrays


    【解决方案1】:

    首先使用.split("\r\n") 拆分行,然后使用shift() 添加对象以弹出行,直到数组清空。代码 sn-p 生成以下数组:

    [
      {
        "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" />

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-23
      • 1970-01-01
      相关资源
      最近更新 更多