So I want to be able to search a CSV file stored on the internet (google drive or google storage bucket) using a key, the CSV file will store a list of names and email addresses.
I need the function to search the CSV file using the name and find the corresponding email address and then store that email address in a variable so I can use it later on.
CSV File Format:
Project Name: Email:
example-project-sandbox example@example.com
I have a non working attempt at this however I think this is a bit long winded and can be done a lot simpler.
$(document).ready(function() {
$.ajax({
type: "GET",
url: "https://storage.googleapis.com/file.csv",
dataType: "text",
success: function(data) {
processData(data);
}
});
});
function processData(allText) {
var allTextLines = allText.split(/
|
/);
var headers = allTextLines[0].split(',');
var lines = [];
for (var i = 1; i < allTextLines.length; i++) {
var data = allTextLines[i].split(',');
if (data.length == headers.length) {
var tarr = [];
for (var j = 0; j < headers.length; j++) {
tarr.push(headers[j] + ":" + data[j]);
}
lines.push(tarr);
}
}
// alert(lines);
}
Any help is greatly appreciated.
Use this library.It will really help parsing the file and save time.
It's very easy check this example.
// Parse CSV string
var data = Papa.parse(csv);
// Convert back to CSV
var csv = Papa.unparse(data);
// Parse local CSV file
Papa.parse(file, {
complete: function(results) {
console.log("Email:", results.email);
}
});
If helped marked the answer and completed. :D
1) Change tarr.push(headers[j]+":"+data[j]);
to tarr.push({name: headers[j], email: data[j]});
2) Loop through tarr
and search for `"whatever-name"``:
var foundEmail;
for (var i = 0; i < tarr.length; i++) {
if (tarr[i].name === "whatever-name") {
foundEmail = tarr[i].email;
break;
}
}
console.log(foundEmail);