問題

我有一個讀檔案指令碼,例如資料

凱文,史密斯,321,街34

女士,別墅,4564,blv 34

Carl, max, 1212, st 34#3

 newDataArray = []

const data = fs.readFileSync('/Users/myuser/Documents/test.txt', 'utf8')

//here I delete  

let response = data.split(/
?
/g)


    //the array is now lenght 3

    response.forEach(element => {
        newDataArray.push(element)   
    });
 

但我最後需要以下內容

     {
      name: 'kevin',
      lastname: 'smith',
      phone: '321',
      add: 'street34' 
    },
    {
      name: 'lady',
      lastname: 'sevilla',
      phone: '4564',
      add: 'blv 34' 
    },
    {
      name: 'carl',
      lastname: 'max',
      phone: '1212',
      add: 'st 34#3' 
    }
 

然後可能在mysql中儲存

 //i dont know how to replace req.body

const { name, lastname, phone, add } = req.body;
    connection.query('INSERT INTO test_table SET ? ',
      {
        name,
        lastname,
        phone,
        add
      }
    , (err, result) => {
      res.redirect('/');
});
 

  最佳答案

簡單如下:

 let response = data.split(/
?
/g)
    .map( row => {
        row = row.split(', ');
        return {
            name: row[0],
            lastname: row[1],
            phone: row[2],
            add: row[3],
        }
    })
 

  相同標籤的其他問題

javascript