elena1234

From JS object to JSON string - JavaScript ( JSON.stringify() )

Aug 22nd, 2021 (edited)
2,567
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // result [{"Town":"Sofia",
  2. // "Latitude":42.7,
  3. // "Longitude":23.32
  4. // },
  5. // {"Town":"Beijing",
  6. // "Latitude":39.91,
  7. //"Longitude":116.36
  8. // }]
  9.  
  10. function solve(arrayOfStrings) { // from stringArray
  11.     arrayOfStrings.shift(); // to remove first line of the array
  12.  
  13.     let newJSONArray = [];
  14.     for (const element of arrayOfStrings) {
  15.         let [empty, townName, lati, longi] = element.split('|');
  16.         let townObject = { // create js object
  17.             Town: townName.trim(),
  18.             Latitude: Number(Number(lati).toFixed(2)),
  19.             Longitude: Number(Number(longi).toFixed(2)),
  20.         }
  21.  
  22.         newJSONArray.push(JSON.stringify(townObject)); // JSON.stringify
  23.     }
  24.  
  25.   return(newJSONArray.join(',\n'))
  26. }
  27.  
  28. solve(['| Town | Latitude | Longitude |',
  29.     '| Sofia | 42.696552 | 23.32601 |',
  30.     '| Beijing | 39.913818 | 116.363625 |']
  31. )
  32.  
  33.  
  34.  
Add Comment
Please, Sign In to add comment