Advertisement
Guest User

Untitled

a guest
Feb 9th, 2016
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. Data records ///"id,first,last,emailn" + "555,John,Doe,jd@gmail.comn" + "666,Jason,scott,js@gmail.comn" + ............
  2.  
  3. var search = init(
  4. "id,first,last,emailn" +
  5. "555,John,Doe,jd@gmail.comn" +
  6. "666,Jason,scott,js@gmail.comn",
  7. "email");
  8.  
  9. search("js@gmail.com"); /// -> {"id":"666","first":"Jason","last":"scott", "email":"js@gmail.com"}
  10.  
  11. function init(text, key) {
  12. var arr = text.split('n'); /// convert text to array
  13. var keyIndex = arr[0].split(',').indexOf(key); /// returns 3
  14.  
  15. return function (value) {
  16. for (var i = 1; i < arr.length; i++) {
  17. var dataLine = arr[i].split(','); /// "666,Jason,scott,js@gmail.comn" to array
  18. if (dataLine[keyIndex] === value) { /// found match between value and id
  19. return convertToObject(arr[0].split(','), dataLine);
  20. }
  21. }
  22. return "not found";
  23. }
  24. }
  25.  
  26.  
  27.  
  28. function convertToObject(indexLine, dataLine) {
  29. /// creates an object from 2 lines: {email: "js@gmail.com",first: "Jason", id: "666", last: "scott"}
  30. var obj = {};
  31. var result = "";
  32. for (var j = 0; j < dataLine.length; j++) {
  33. obj[indexLine[j]] = dataLine[j];
  34. }
  35. return JSON.stringify(obj); /// String format;
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement