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

89
Visualizações
override given variable in object | Javascript React
const [letters, setLetters] = useState({
    A: false,
    B: false,
    C: false
})

function handleClick(input){
    setLetters((prevLetters) => ({
        ...prevLetters,
        [input]: true
    }))
}

handleClick("A")

How do I manage that, depending on the input, the correct letter is set to true? So if the input is A, it should be set to true in the letters object.

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

0

I think a Map would be a good choice here.

const [letters, setLetters] = useState(new Map());

function handleClick (input) {
    setLetters(letters.set(input, true));
}

handleClick("A");

If you wish that input MUST be A, B, or C, then you can use an if statement:

const [letters, setLetters] = useState(new Map([
    ["A", false], // default values for map
    ["B", false],
    ["C", false],
]));

function handleClick (input) {
    if (!letters.has(input)) return; // if map doesnt have it, stop

    setLetters(letters.set(input, true));

    // can also use letters.set(input, false) to "turn it off"
}

handleClick("A");
about 4 years ago · Juan Pablo Isaza Relatório

0

If you want to override the existing properties on the letters object you can do something like this

const lettersObject = {
  A: false,
  B: false,
  C: false,
};

const [letters, setLetters] = useState(lettersObject);

function handleClick(input) {
  setLetters({
    ...lettersObject,
    [input]: true,
  });
}
about 4 years ago · Juan Pablo Isaza Relatório

0

Is this what you are looking for?

  function handleClick(input) {
    setLetters((prevLetters) => ({
      letters: {
        ...prevLetters,
        input: true
      }
    }));
  }
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