Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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);
- }
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement