猿问

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

客观的

我想制作这个程序,以便它可以从文本文件中读取数据并将数据存储到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, 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


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


FFIVE
浏览 136回答 1
1回答

慕容森

尝试这个您可以获得 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, 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`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)
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答