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

173
Views
Cómo agregar valor a una matriz de objetos en reaccionar

Quiero cambiar el valor del objeto de índice 0 'sm: verdadero' y en la segunda verificación crear un nuevo objeto y cambiar el valor de 'xl: verdadero' del índice 1

 const [size, setSizes] = useState([{sm:false, md:false, lg:false, xl:false,}]) const sizeHandler=(index, value)=> { on first check index is 0 & value = sm:true on secondcheck index is 1 & value = xl:true if(index===0 size.map(()=>{ setSize() }) }
 <FormGroup> <FormControlLabel control={<Checkbox />} label="SM" onChange={()=>sizeHandler(0,{sm:true})} /> </FormGroup> <FormGroup> <FormControlLabel control={<Checkbox />} label="XL" onChange={()=>sizeHandler(1,{xl:true})} /> </FormGroup>

el resultado debería ser así: [{sm:true, md:false, lg:false, xl:false}, {sm:false, md:false, lg:false, xl:true}]

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

0

Soy relativamente nuevo en js, así que espero que alguien más sabio actualice/corrija este intento de respuesta a continuación.

Sin entrar en la interfaz de usuario (FormGroup, FormControlLabel), intentará centrarse en la tarea/requisito real en cuestión.

Dado:

  1. Una matriz, inicialmente de tamaño 1, con un objeto que tiene 4 propiedades específicas.
  2. El tamaño de la matriz puede aumentar (no estoy seguro si también disminuirá) y si se invoca con el índice '1' (aunque el tamaño de la matriz sea 1), no debe haber ningún error

Requisito: según el 'índice', cree elementos de matriz adicionales y actualice el elemento correspondiente (por ejemplo, si 'índice' es 1, luego actualice el segundo elemento) con el valor que se envía para reemplazar solo una parte del objeto identificado en la posición 'índice'.

Fragmento para una comprobación rápida:

 const fixedObj = { sm: false, md: false, lg: false, xl: false }; const dynamicArray = [fixedObj]; /* const [size, setSizes] = useState([{sm:false, md:false, lg:false, xl:false,}]) */ const sizeHandler = (index, value) => { // First capture the current array-length const currArrLen = dynamicArray.length; if (!(index < currArrLen)) { // if 'index' is NOT within the array-length for (let i = currArrLen; i < index; i++) { // increase the array-size to match index dynamicArray.push(fixedObj); // initialize each new array-element using the fixedObj tempate }; }; // Now, target the specific array-element, use spread operator to use template, followed by 'value' // and update the specific array-element. dynamicArray[index] = { ...fixedObj, ...value }; }; sizeHandler(0, { sm: true }); console.log('on first check, update sm to true at index 0, array: ', dynamicArray, '\n\n\n'); sizeHandler(1, { xl: true }); console.log('on second check update xl to true at index 1, array: ', dynamicArray, '\n\n\n');

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!