svephoto

Towns to JSON [JavaScript]

Sep 23rd, 2021 (edited)
848
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function towns(array = []) {
  2.     class Town {
  3.         constructor(name, latitude, longitude) {
  4.             this.name = name;
  5.             this.latitude = latitude;
  6.             this.longitude = longitude;
  7.         }
  8.     }
  9.  
  10.     let result = [];
  11.  
  12.     for (let i = 1; i < array.length; i++) {
  13.         let arr = array[i].split("|");
  14.         let name = arr[1].trim();
  15.         let latitude = (+arr[2].trim()).toFixed(2);
  16.         let longitude = (+arr[3].trim()).toFixed(2);
  17.      
  18.         let town = new Town(name, latitude, longitude);
  19.  
  20.         let townForJSON = {};
  21.  
  22.         townForJSON["Town"] = town.name;
  23.         townForJSON["Latitude"] = town.latitude;
  24.         townForJSON["Longitude"] = town.longitude;
  25.  
  26.         let objectToJSON = JSON.stringify(townForJSON, function (key, value) {
  27.             if (key == "Latitude") {
  28.                 return Number(value);
  29.             } else if (key == "Longitude") {
  30.                 return Number(value);
  31.             } else {
  32.                 return value;
  33.             }
  34.         });
  35.  
  36.         result.push(objectToJSON);      
  37.     }
  38.  
  39.     console.log("[" + result.join(",") + "]");
  40. }
  41.  
Add Comment
Please, Sign In to add comment