Search code examples
javascriptarraysjsonbixby

Split a JSON array into JS variables - Bixby


So I have a API outputting JSON to my JS code (http://api.opentripmap.com/0.1/ru/places/bbox?lon_min=-123.049641&lat_min=37.550392&lon_max=-122.049641&lat_max=38.550392&kinds=foods&format=geojson&apikey=5ae2e3f221c38a28845f05b685eac8210f10fb196793a9d4f6653c25).

However it contains a JSON Array that looks like this- "coordinates": [ -122.510216, 37.769474 ]

Is there a way to split it into separate JS variables like one variable for the left side and another for the right side. At the moment the array is causing my code to crash as it can only accept one input in each slot.

Sorry If this is a simple question, I haven't been able to solve this yet...

EDIT: Sorry for the terrible question layout. I have tried to splice and splitting the array with no success (splicing lead to a whole load of undefined errors).

My current code is

module.exports.function = function findLunch(myLocation) {
  var loc_long_max = Number(myLocation.longitude) //grab longitude from user
  var loc_lat_min = Number(myLocation.latitude) //grab latitude from User
  var loc_long_min = loc_long_max - 0.5;
  var loc_lat_max = loc_lat_min + 0.5;

  var url_all = "http://api.opentripmap.com/0.1/ru/places/bbox?lon_min=" + loc_long_min + "&lat_min=" + loc_lat_min + "&lon_max=" + loc_long_max + "&lat_max=" + loc_lat_max + "&kinds=foods&format=geojson&apikey=5ae2e3f221c38a28845f05b685eac8210f10fb196793a9d4f6653c25"
  var results = http.getUrl(url_all, { format: 'json' }); //gets json info from url_all.

  console.log(results.features[rand].properties.name)
  //console.log(results.feautres[rand].properties.rate)
   console.log(results.features[rand].geometry.coordinates)
  //console.log(results);

  for (var i = rand; i < results.features.length; i++) {
    console.log(results.features[rand].properties.name)
    console.log(results.features[rand].properties.rate) 
    var businesses = {
      name: results.features[rand].properties.name,
      rating:results.features[rand].properties.rate,
      coordinates: results.features[rand].geometry.coordinates
    }
  }

  return businesses

So the coordinates need to be split and then be in the businesses var which is then outputted to Bixby....

EDIT 2 : Fixed it - thanks everyone for the help!

Thanks!


Solution

  • Not sure if this is smth you're asking but you can use destructuting assignment to assign items in an array to variables:

    const coordinates = [ -122.510216, 37.769474  ];
    const [coordinateOne, coordinateTwo] = coordinates;
    
    console.log(coordinateOne) // -122.510216
    console.log(coordinateTwo) // 37.769474