我有一个csv
文件,其中一行有时有一列有两个值。目前我正在尝试使用拆分,,
但没有按预期工作。有人可以阐明如何实现预期的输出。我不想使用任何npm
库。
//users.csv
name,age,hobbies
james,20,"reading,playing"
marie,18,singing
peter,19,watching movies
//index.js
const fs = require('fs');
const {promisify} = require("util");
const readFile = promisify(fs.readFile)
const readSheet = async () =>{
const result = await readFile("./users.csv", "utf-8");
const csv = result.split("\n").map(ele=>ele.split(","))
let keys = csv.slice(0,1)[0];
const values = csv.slice(1)
keys.map(keys=>keys.split(''))
let usersArr = [];
for(let i = 0;i<values.length;i++){
let usersObj = {};
keys.forEach((key,j)=>usersObj[key] = values[i][j])
usersArr.push(usersObj)
}
return usersArr
}
//current output
[ { name: 'james', age: '20', hobbies: '"reading' },
{ name: 'marie', age: '18', hobbies: 'singing' },
{ name: 'peter', age: '19', hobbies: 'watching movies' } ]
//expected output object
[
{
"name": "james",
"age": 20,
"hobbies": ["reading","playing"]
},
{
"name": "marie",
"age": 18,
"hobbies": ["singing"]
},
{
"name": "peter",
"age": 19,
"hobbies": ["watching movies"]
}
]