Home > Software engineering >  Prevent original array from getting changed
Prevent original array from getting changed

Time:04-12

I have an array that consists of some geoJSON data. I want to create a new array consisting of the data with one more key in the properties section. But it keep changing the original array. How can I prevent it from changing the orignial array?

const [citys, setCitys] = useState(someGeoJson)
const [manipulatedArray, setManipulatedArray] = useState([])

function createManiArray() {
  let currentManipulatedArray = []
  citys.features.forEach((city) => {
    let currentCity = city
    currentCity.properties = { ...city.properties,
      value: Math.random()
    }
    currentManipulatedArray .push(currentCity)
    //My problem now is that this changes the orginal city array, how can i prevent that from happening?

  })
  setManipulatedArray(currentManipulatedArray)
}

CodePudding user response:

I think many of this kind of problems arise in the moment you use a forEach to essentially map values to another list. The "map" method on an array does exactly that

const manipulated = citys.map(city => ({
    ...city.properties,
    value: Math.random
}));

This way you don't have to worry about references / modifying your original array.

P.S. it is also worth noting that storing a variable with useState that's essentially derived from another state variable is not an ideal thing to do. You might want to reconsider how your state is managed to essentially have a single source of truth (being your "citys") variable :)

CodePudding user response:

  1. You're not using setManipulatedArray to set the state.

  2. You should be using map to create a new array of objects instead of mutating the original array.

const [cities, setCities] = useState(someGeoJson);

const [manipulatedArray, setManipulatedArray] = useState([]);

function createManiArray() {

  // Create a new array of objects with an updated
  // properties object
  const updated = cities.features.map(city => {
    return {
      ...city,
      properties: {
        ...city.properties,
        value: Math.random()
      }
    };
  });
  
  // Set the new state with that array
  setManipulatedArray(updated);

}

  • Related