Search code examples
jsonreact-nativereact-hooksexpogeolocation

Building a partial JSON from another JSON using variables


I'm using the expo-location lib's getCurrentPositionAsync in my react-native project:

result = await Location.getCurrentPositionAsync();

to get the current GPS position.

Now the result variable will hold this JSON object:

Object {
  "coords": Object {
    "accuracy": 603,
    "altitude": 0,
    "altitudeAccuracy": 0,
    "heading": 0,
    "latitude": 37.421988,
    "longitude": -122.0840207,
    "speed": 0,
  },
  "mocked": false,
  "timestamp": 1677233557987,
}

I need to save the latitude and longitude values from the result variable to the state variable location using the state function:

setLocation({latitude, longitude});

So when I run:

console.log(location);

It will show this:

Object {
  "latitude": 37.421988,
  "longitude": -122.0840207,
}

For now the only success I've had was doing this:

const latitude = result['coords'].latitude;
const longitude = result['coords'].longitude;

setLocation({latitude, longitude});

My question is - if there is a more direct way of doing this ? like:

setLocation({result['coords'].latitude, result['coords'].longitude}); 

Because this doesn't work.

Thanks.


Solution

  • You missed the keys when tried to set the location state. This should work:

    setLocation({
      latitude: result['coords'].latitude,
      longitude: result['coords'].longitude,
    }); 
    

    Alternatively, you can use destructuring to extract the latitude and longitude values from the result.coords object:

    const { latitude, longitude } = result.coords;
    setLocation({ latitude, longitude });
    

    This is more cleaner way to achieve the same result.