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

163
Views
¿Por qué todos los objetos tienen la misma fecha a pesar de incrementarse en cada iteración?

Hola, quiero poder modificar una matriz de objetos en estado usando un bucle for y me gustaría saber la mejor manera de hacerlo.

 const [ paymentData, setPaymentData ] = useState([ { paymentN: 'First Payment', paymentDate: 'March 07' }, { paymentN: 'Second Payment', paymentDate: 'March 24' }, { paymentN: 'Third Payment', paymentDate: 'April 8th', }, { paymentN: 'Fourth Payment', paymentDate: 'April 21st' } ])

Específicamente, quiero modificar las fechas en cada objeto en mi matriz de estado de datos de pago. Mi resultado final previsto sería algo así como

 { paymentN: 'First Payment', paymentDate: 'Mon Mar 14 2022 07:17:05 GMT-0400' }, { paymentN: 'Second Payment', paymentDate: 'Mon Mar 28 2022 07:17:05 GMT-0400' }, { paymentN: 'Third Payment', paymentDate: 'Mon Apr 11 2022 07:17:05 GMT-0400' }, { paymentN: 'Fourth Payment', paymentDate: 'Mon Apr 25 2022 07:17:05 GMT-0400' }

Mi función está destinada a obtener la fecha actual, incrementarla en 2 semanas y luego establecer la nueva fecha en el objeto [i]. Mi idea era tomar los datos de estado anteriores, crear una nueva matriz de objetos con la fecha de modificación y establecerla de nuevo.

 const createPaymentPlan = ( amount, e ) => { e.preventDefault(); const currentDate = new Date() var obj = [] for ( let i = 0 ; i < 4 ; i ++ ) { currentDate.setDate(currentDate.getDate()+14) const updatedPaymentData = paymentData[i] updatedPaymentData.paymentDate = currentDate obj.push(updatedPaymentData) } setPaymentData(obj) }

Cuando probé esto, mi estado final se ve así, sin embargo, cuando consola. registro la variable de datos de pago actualizados, se establece en la fecha incrementada correcta en cada bucle.

¿Por qué mi estado se ve así donde todas las fechas de pago son iguales a

ingrese la descripción de la imagen aquí

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Cada objeto se refiere al mismo objeto de fecha, lo que hace que todos tengan la misma fecha después del bucle. Puede crear una nueva fecha en cada iteración para solucionar este problema.

 const paymentData = [{ paymentN: 'First Payment', paymentDate: 'March 07' }, { paymentN: 'Second Payment', paymentDate: 'March 24' }, { paymentN: 'Third Payment', paymentDate: 'April 8th', }, { paymentN: 'Fourth Payment', paymentDate: 'April 21st' } ] const currentDate = new Date() const array = [] for (let i = 0; i < paymentData.length; i++) { currentDate.setDate(currentDate.getDate() + 14) const updatedPaymentData = paymentData[i] updatedPaymentData.paymentDate = new Date(currentDate); array.push(updatedPaymentData) } console.log(array)


Es mejor asegurarse de que los valores del estado sean del mismo tipo/formato en todas las representaciones para que pueda hacer esta conversión y usar la matriz convertida como el estado inicial.

 // this can be defined somewhere outside the component const formatPaymentData = (paymentData) => { return paymentData.reduce( ((currentDate) => (formatted, curr) => { currentDate.setDate(currentDate.getDate() + 14); formatted.push({ ...curr, paymentDate: new Date(currentDate) }); return formatted; })(new Date()), [] ); }; const [paymentData, setPaymentData] = useState( formatPaymentData([ { paymentN: 'First Payment', paymentDate: 'March 07', }, { paymentN: 'Second Payment', paymentDate: 'March 24', }, { paymentN: 'Third Payment', paymentDate: 'April 8th', }, { paymentN: 'Fourth Payment', paymentDate: 'April 21st', }, ]) );
about 4 years ago · Juan Pablo Isaza Report

0

const createPaymentPlan = ( amount, e ) => { e.preventDefault(); let currentDate=new Date(); let finalPayment=paymentData.map((e)=>{ currentDate=new Date(new Date().setDate(currentDate.getDate()+1)) e.paymentDate=currentDate; return e }) setPaymentData(finalPayment); }
about 4 years ago · Juan Pablo Isaza 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!