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

289
Views
Evitar que se cambie la matriz original

Tengo una matriz que consta de algunos datos geoJSON. Quiero crear una nueva matriz que consista en los datos con una clave más en la sección de propiedades. Pero sigue cambiando la matriz original. ¿Cómo puedo evitar que cambie la matriz original?

 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

Creo que muchos de este tipo de problemas surgen en el momento en que usas un forEach para asignar esencialmente valores a otra lista. El método "mapa" en una matriz hace exactamente eso

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

De esta manera, no tiene que preocuparse por las referencias/modificar su matriz original.

PD: también vale la pena señalar que almacenar una variable con useState que se deriva esencialmente de otra variable de estado no es lo ideal. Es posible que desee reconsiderar cómo se gestiona su estado para tener esencialmente una única fuente de verdad (siendo su variable "ciudades") :)

about 4 years ago · Santiago Gelvez Report

0

  1. No está utilizando setManipulatedArray para establecer el estado.

  2. Debería usar el map para crear una nueva matriz de objetos en lugar de mutar la matriz original.

 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!