Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

174
Visualizações
How to add value to an array of objects in react

I want to change value of index 0 object 'sm:true' and on second check create a new object and change value of 'xl:true' of index 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>

result should be like this: [{sm:true, md:false, lg:false, xl:false}, {sm:false, md:false, lg:false, xl:true}]

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I'm relatively new to js - so hopefully, someone wiser will update/correct this attempted-answer below.

Without going into the UI (FormGroup, FormControlLabel), will try to focus on the actual task/requirement at hand.

Given:

  1. An array, initially of size 1, with one object that has 4 specific properties.
  2. Array size may increase (not sure if it will decrease as well) and if invoked with index '1' (even though array-size is 1), there must not be any error

Requirement: Based on the 'index', create additional array-element/s and update the corresponding element (for example if 'index' is 1, then update the 2nd element) with the value being sent used to replace only a part of the object identified at 'index' position.

Snippet for quick-checking:

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda