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

113
Visualizações
Is there any way that I can add another value to a key in an object within React?

I will have a list of objects that are going to be entered by an input field. I have it working where it will create the list of objects, but when I try to add another value to one of the objects that already exist. It will just replace the previous value within it.

Current output when I console.log()

const [ tags, setTags ] = useState({
1: 'hello',
2: 'world',
3: 'goodbye'
})

My expected output if person 1 adds the tag 'testing'.

const [ tags, setTags ] = useState({
1: ['hello', 'testing'],
2: 'world',
3: 'goodbye'
})

The function that I have so far that is taking the value from the input. A is an id number and B is the new tag.

function updateTags(a, b){

  if(tags.hasOwnProperty(a)){
    setTags((prevTags) => {
      return {
        ...prevTags,
        [a]: ????
      }
    })
  }else{
    setTags((prevTags) => {
      return {
        ...prevTags,
        [a]: b
      }
    })
  }

If you need more information please let me know.

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

0

I think this should work

function updateTags(a, b){

  if(tags.hasOwnProperty(a)){
    setTags((prevTags) => {
      return {
        ...prevTags,
        [a]: Array.isArray(prevTags[a]) ? [...prevTags[a], b] : [prevTags[a], b]
      }
    })
  } else {
    setTags((prevTags) => {
      return {
        ...prevTags,
        [a]: b
      }
    })
  }
about 4 years ago · Juan Pablo Isaza Relatório

0

I think you can use approach like this:

updateTags = (key, tag) => 
    setTags((prevTags) => ({ 
        ...prevTags,
        [key]: prevTags[key] ? [prevTags[key], tag].flat() : tag,
    }));
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