Skip to content

Instantly share code, notes, and snippets.

@beeekind
Created February 11, 2016 08:04
Show Gist options
  • Save beeekind/4da98402f5f91c1ab988 to your computer and use it in GitHub Desktop.
Save beeekind/4da98402f5f91c1ab988 to your computer and use it in GitHub Desktop.
AngularJS service which takes a raw csv file via the HTML5 file api and returns an array of contact objects. Agnostic to ordering of the csv, and providing hard coded aliases for key words such as firstName which might also be called first_name in the csv.
angular.module('handstack').service("InterpreterService", function(){
this.getContactsFromRawCSV = function(file, callback){
/**
* Take CSV in a format similar to:
*
* '
* firstName,lastName,phone,email
* ben,jones,1234,b@b.com
* jessica,lee,2345,j@j.com
* '
*
* and output an array similar to
*
* '
* [
* {
* name:"ben jones",
* phone: "1234",
* email: "b@b.com"
* },
* {
* name:"ben jones",
* phone: "1234",
* email: "b@b.com"
* }
* ]
* '
*
* The order of the values of the CSV should not matter. Also the legend object defines acceptable key names,
* first example the key "phoneNumber" will translate to the phone property of the outputted object.
*/
let reader = new FileReader();
let legend = {
"firstName": ["first name", "first_name", "firstName", "First Name", "first"],
"lastName": ["last name", "last_name", "lastName", "Last Name", "last"],
"phone": ["phone number", "phone_number", "phoneNumber", "Phone Number", "Number", "number", "phone", "Phone"],
"email": ["email", "email_address", "emailAddress", "Email Address", "Email"]
};
let key = {};
reader.onload = (event) => {
let csvString = event.currentTarget.result;
let lines = csvString.split(/\r\n|\n/);
// build our legend-key based on the labels provided in the first line of the csv
let labels = lines.shift().split(','); // INEFFICIENT FOR LARGE ARRAYS
let index = 0;
labels.forEach((label) => {
_.each(legend, (legendValue, legendKey) => {
console.log(label, legendKey, legendValue, _.contains(legendValue, label));
if(_.contains(legendValue, label)){
console.log(legendKey + " found!");
key[index] = legendKey;
}
});
console.log(key);
index++;
});
// based on our legend key, map each remaining line of the csv into a contact object
let contacts = lines
.map((line) => line.split(','))
.map((arrayOfValues) => {
let contact = {};
_.each(key, (keyValue, keyKey) => {
contact[keyValue] = arrayOfValues[keyKey];
});
return contact;
})
.map((contactObject) => {
contactObject.name = contactObject.firstName + " " + contactObject.lastName;
delete contactObject.firstName;
delete contactObject.lastName;
if (contactObject.phone) return contactObject;
})
.filter((item) => (item !== undefined));
console.log(contacts);
callback(contacts);
};
reader.readAsText(file);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment