Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

126
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda