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

141
Vistas
Conditionally add key/value pairs of two separate objects (one in array within initial state) for array method inside of useState() hook

Right now, this doesn't work.

const item = {name: "mike", apples: 20}

const [list, setList] = useState([{name: "peter", apples: 30}, {name: "mike", apples: 39}])

setList(list.map(entry => entry.name == item.name ? entry.apples = item.apples+entry.apples : entry = entry))

I am able to get it working with the code below. I know it's not clean and that's why I'm trying to get the top code working the react way: using es6 within useState hook.

  let newList = [...list]
  let changed = false
  newList.map(entry => {
    if(entry.name == item.name) {
      entry.apples = item.apples+entry.apples
    }
  if(changed) {
    setList(newList)
  }

Edit: I've also tried functional update on the state like below

setList(list => list.map(entry => entry.name == item.name ? entry.apples = item.apples+entry.apples : entry = entry))
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Here's the right way:

setList((previousList) =>
  previousList.map((entry) =>
    entry.name == item.name
      ? { ...entry, apples: entry.apples + item.apples }
      : entry
  )
);

entry.name == item.name ? entry.apples = item.apples+entry.apples

will not work because entry.apples = item.apples+entry.apples returns apples, but each element of the array should remain an object and you should also make sure that the state is not mutated (entry.apples = ... is bad because entry is mutated)

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