0

I have an object like this

this.currentRegion = {
    latitude: 25.3170013,
    longitude: 55.4748285,
    latitudeDelta: LATITUDE_DELTA,
    longitudeDelta: LONGITUDE_DELTA,
};

and another object

coords = {
    accuracy: 20,
    altitude: 5,
    heading: 0,
    latitude: 25.380599999999998,
    longitude: 55.3992,
    speed: 0,
}

I need

this.currentRegion = {
    latitude: 25.380599999999998,
    longitude: 55.3992,
    latitudeDelta: LATITUDE_DELTA,
    longitudeDelta: LONGITUDE_DELTA,
}

I tried this.currentRegion = Object.assign(this.currentRegion, region.coords); and got the error

Attempting to set key on an object that is immutable and has been frozen

Vaibhav Vishal
  • 6,576
  • 7
  • 27
  • 48
Alice Bob
  • 223
  • 1
  • 2
  • 6

4 Answers4

3
this.currentRegion = {...this.currentRegion, latitude: coords.latitude, longitude: coords.longitude}
Idan
  • 3,604
  • 1
  • 28
  • 33
0

Try

this.currentRegion.latitude = coords.latitude
this.currentRegion.longitude = coords.longitude
this.currentRegion.latitudeDelta = coords.latitudeDelta
this.currentRegion.longitudeDelta = coords.longitudeDelta
Il Maro
  • 21
  • 6
0

If you are trying that in React use this.setState({currentRegion : ...this.currentRegion, latitude: coords.latitude, longitude: coords.longitude })

why use setState instead of this.state

NEVER mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.

For further discussion check here : What the difference of this.state and this.setstate in ReactJS?

Hemanath
  • 1,075
  • 6
  • 15
-1

As with so many problems, you can solve this using Array.prototype.reduce. The benefit of this solution is that you don't have to hardcode which fields you want to transfer — it will simply overwrite any fields that already exist.

let currentRegion = {
  latitude: 25.3170013,
  longitude: 55.4748285,
  latitudeDelta: 123,
  longitudeDelta: 456,
};

const coords = {
  accuracy: 20,
  altitude: 5,
  heading: 0,
  latitude: 25.380599999999998,
  longitude: 55.3992,
  speed: 0,
};

console.log(currentRegion);

currentRegion = Object.keys(coords).reduce((acc, val) => {
  if (typeof acc[val] !== 'undefined') {
    acc[val] = coords[val];
  }

  return acc;
}, currentRegion);

console.log(currentRegion);
korona
  • 2,308
  • 1
  • 22
  • 37