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

183
Views
Ordenar claves/valores de objetos por una matriz de objetos a partir de los cuales se crea el objeto

Así que estoy generando un formulario para que los usuarios de mi aplicación lo completen a partir de una serie de objetos, cada objeto tiene sus propios datos de validación... etc. Este problema es cuando el usuario completa el formulario y se crea un nuevo objeto a partir de él para enviarlo al back-end, si el usuario completa el formulario en orden, el objeto está en el orden correcto, pero si el usuario regresa y cambia un valor, el objeto se pone fuera de servicio.
Objeto original:

 const formData = [ { name: 'One', validation: 'Number', }, { name: 'Two', validation: 'Number', }, { name: 'Three', validation: 'Number', }, { name: 'Four', validation: 'Number', }

El nuevo Objeto está construido con un método de cambio de identificador.
Manejador de objetos:

 const [newForm, setNewForm] = useState({}) const handleChange = (e) => { const { name, value } = e.target setNewForm({ ...newForm, [name]: parseFloat(Number(value).toFixed(2)) }) }

Objeto correcto:

 newForm = { One: 1, Two: 2, Three: 3, Four: 4, }

Objeto incorrecto:

 newForm = { Two: 2, One: 1, Four: 4, Three: 3, }

Me está costando encontrar una manera de comparar el nuevo formulario con formData para asegurarme de que permanezcan en el orden correcto. Si alguien pudiera darme algún consejo y ayudarme se lo agradecería.

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

0

Va a tener un problema con su estado, es posible que no obtenga el estado anterior o newForm debido al comportamiento asincrónico de useState . Vas a querer usar una función de flecha con un parámetro para tu estado anterior para obtener el estado anterior. Como esto:

 setNewForm((prevState) => ({ ...prevState, [name]: parseFloat(Number(value).toFixed(2)) }))

También aquí hay un código de mi repositorio de github para comparar objetos

 /* Step 1: Check if both objects have same number of keys */ function keyNum(k1, k2) { return k1.length === k2.length ? true : false; } /* Step 2: put objects in the correct order */ function changeOrder(o1, o2) { /* This will check that all keys are equal and exist also * The first object's keys will look like this in array form: [a, b, c, d] * The next object's keys will probably be out of order relative to the first object's keys: [b, d, a, c] * The iterator will start on the first key of the first array and find it in the second, and create a new object in order * * Example of first iteration: * * (values of each key will obviously come with the key) * * ▼ * [a, b, c, d] * * ▼ * [b, d, a, c] * * new: * [a] * */ let newObj = {}; let equal = false; let baseObjKeys = Object.keys(o1); let returnObj = { newObj: "", equal: equal } for(let i = 0; i < baseObjKeys.length; i++) { if(typeof o2[baseObjKeys[i]] === 'undefined') { return returnObj; } newObj[baseObjKeys[i]] = o2[baseObjKeys[i]]; } equal = true; returnObj = { newObj: newObj, equal: equal } return returnObj; } /* Step 3: Check if all the values with respect to their corresponding keys are equal */ function valEqu(o1, o2, k1) { for(let i = 0; i < k1.length; i++) { if(o1[k1[i]] !== o2[k1[i]]) { console.log('ran'); return false; } } return true; } /* If all of these checks pass, the objects are equal. */ export default function compareObj (o1, o2) { let k1 = Object.getOwnPropertyNames(o1); let k2 = Object.getOwnPropertyNames(o2); let keyNumB = keyNum(k1, k2); let changeOrderB = changeOrder(o1, o2); // let keyEquB = keyEqu(k1, k2); let valEquB = valEqu(o1, changeOrderB.newObj, k1); if(keyNumB === true && changeOrderB.equal === true && valEquB === true) { return true; } return false; }

Espero que esto ayude.

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!