I have this format csv file
Name | Email | Contact | Designation | Address
where Name, Email and contact is fixed field but Designation or address or any other fields user can add in csv file while uploading
Code to upload CSV
async uploadCSV(ev){
const reader = new FileReader();
const file = ev.target.files[0];
var file_name = file.name.split(".");
var file_ext = file_name[file_name.length - 1].toLowerCase();
if (file_ext !== "csv") {
return this.toaster.error("Please upload csv file");
} else {
var output;
reader.onload = () => {
var csvToText = reader.result;
output = this.csvToJSON(csvToText);
};
reader.readAsText(file);
await new Promise((f) => setTimeout(f, 2000));
}
}
dataSource = [];
csvToJSON(csv) {
var lines = csv.split("n");
var result = [];
var headers;
var fileType;
headers = lines[0].split(",");
headers = headers.map((s) => s.replace(/n|t|r/gm, ""), headers);
for (var i = 1; i < lines.length; i++) {
console.log("lines ---", lines);
let obj = {};
if (lines[i] == undefined || lines[i].trim() == "") {
continue;
}
var words = lines[i].split(",");
for (var j = 0; j < words.length; j++) {
let name;
let lname;
let userEmail;
let userPhone='-';
let nameIndex = headers.indexOf("Name");
let contactIndex = headers.indexOf("Contact");
let emailIndex= headers.indexOf("Email");
name=nameIndex != -1 ? words[nameIndex].replace(/n|t|r/gm, "") : "";
userEmail=emailIndex != -1 ? words[emailIndex].replace(/n|t|r/gm, "") : "";
userPhone=phoneIndex != -1 ? words[contactIndex].replace(/n|t|r/gm, "") : "";
console.log('words length ----> ');
console.log('words',words);
/* End */
obj = {
Name: name,
Email:userEmail,
MobileNumber: userPhone,
jsonData: '',
};
}
result.push(obj);
}
this.dataSource = result;
console.log("datadource ", this.dataSource);
}
i’m fetching these three fixed fields but i want to fetch other dynamic fields and it’s values like if it is a designation then
{designation : ‘Manager’,address:’UK’,…}
and pass it to json data
any solution Thanks