亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 JavaScript 中將文本文件讀入對象數組

如何在 JavaScript 中將文本文件讀入對象數組

UYOU 2023-04-14 17:33:03
我無法找到解決問題的最佳方法。我想將一個文本文件讀入一個對象數組。數組的格式是固定的,但如果文本文件有更好的格式,那是可能的。我目前擁有的文本文件具有以下結構:item_tag = milkitem_date = 2020-10-25item_quantity = 1*item_tag = eggitem_date = 2020-10-04item_quantity = 3*item_tag = bananaitem_date = 2020-10-03item_quantity = 2*item_tag = appleitem_date = 2020-10-10item_quantity = 1*item_tag = yoghurtitem_date = 2020-10-31item_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}];我見過其他類似的問題(例如this和this),但這些不是針對對象數組的。這些解決方案也都使用 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]); }) 如果可能,我如何修改它以將文本轉換為對象數組?謝謝你的幫助!另外,是否也可以將數組(現已修改)轉回文本文件?
查看完整描述

1 回答

?
慕雪6442864

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


查看完整回答
反對 回復 2023-04-14
  • 1 回答
  • 0 關注
  • 112 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號