为了账号安全,请及时绑定邮箱和手机立即绑定

从文本文件读取数据并将其存储在对象数组中 - NodeJS

从文本文件读取数据并将其存储在对象数组中 - NodeJS

FFIVE 2023-11-02 17:12:18
客观的我想制作这个程序,以便它可以从文本文件中读取数据并将数据存储到Array of Objects.下面显示的格式是该文本文件将采用的格式,如果可能的话,应修剪逗号后面的空格,但不是完整的字符串。因此,当该程序运行时,它将把内容推送到一个数组中,该数组稍后可以在程序中用作array.map().示例文本文件//file.txt (Note: The main file will always be in this exact format)John Doe, 01/30/2000, This is the Address, Los Angeles, CA, 70077 Jane Doe, 01/30/2000, This is the Address, Los Angeles, CA, 70077Arlong Doe, 01/30/2000, This is the Address, Los Angeles, CA, 70077Mark Doe, 01/30/2000, This is the Address, Los Angeles, CA, 70077Bill Doe, 01/30/2000, This is the Address, Los Angeles, CA, 70077// format: [ firstname lastname, date of birth (MM/DD/YYYY), Address, City, State, Zip]期望输出array = [  {    firstname: "John",    lastname: "Doe",    dob: '01/30/2000',    address: 'This is the Address',    city: "Los Angeles",    state: "CA",    zip: "70077"  },  {    firstname: "Jane",    lastname: "Doe",    dob: '01/30/2000',    address: 'This is the Address',    city: "Los Angeles",    state: "CA",    zip: "70077"  },  {    firstname: "Arlong",    lastname: "Doe",    dob: '01/30/2000',    address: 'This is the Address',    city: "Los Angeles",    state: "CA",    zip: "70077"  }] //and so on
查看完整描述

1 回答

?
慕容森

TA贡献1853条经验 获得超18个赞

尝试这个


您可以获得 csv 解析器,但如果您确定这是格式,则可以节省一些千字节


const csv = `John Doe, 01/30/2000, This is the Address, Los Angeles, CA, 70077 

Jane Doe, 01/30/2000, This is the Address, Los Angeles, CA, 70077

Arlong Doe, 01/30/2000, This is the Address, Los Angeles, CA, 70077

Mark Doe, 01/30/2000, This is the Address, Los Angeles, CA, 70077

Bill Doe, 01/30/2000, This is the Address, Los Angeles, CA, 70077`


const obj = csv.split(/\n/).map(line => {

  const [name, dob, Address, City, State, Zip] = line.split(", ")

  const [firstname, lastname] = name.split(" ");

  return { firstname, lastname, dob, Address, City, State, Zip: Zip.trim() }

});


console.log(obj)


查看完整回答
反对 回复 2023-11-02
  • 1 回答
  • 0 关注
  • 135 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信