Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

281
Views
Prevent original array from getting changed

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)
}
about 4 years ago · Santiago Gelvez
2 answers
Answer question

0

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 :)

about 4 years ago · Santiago Gelvez Report

0

  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);

}

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!