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

112
Vistas
Iterate a property of Object in Array that Matches Query

I'm working in React and want to iterate the 'amount' property an Object in my 'cart' array based on if it matches the item that had the 'iterate' button pressed.

My original solution was this...

setCart((cart) => {
  const itemMatch = cart.find((cartItem) => cartItem.name === item.name);
  if (itemMatch !== undefined) {
    itemMatch.amount = itemMatch.amount + 1;
  } else {
    cart.push(item);
  }

  return [...cart];
})

However, the iteration was counting by two's.

My second solution was this...

setCart((cart) => {
  const updatedCart = cart.map((cartItem) => {
    if (cartItem.name === item.name) {
      return {...cartItem, amount: cartItem.amount + item.amount}
    } else {
      return cartItem
    }
  })

  return updatedCart;
})

This solution works but I can't figure out what the difference between these two is. If anyone could help explain the difference that would really help me understand. Thanks.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

In first solution you push items in already existing array which already have all those items.

offtop: Second solution is also better in terms of not mutating existing data.

about 4 years ago · Juan Pablo Isaza Denunciar

0

In here you're doing different stuff.

Lets suppose you have a sample input like this:

const item = { name: "abc", amount: 5 }
const cart = [
    { name: "ab", amount: 15 },
    { name: "def", amount: 10 }
]

In Scenario 1:

const setCart = ((cart) => {
    /* first finding if the object which are already exist in cart array
     is also exist in item object or not. */
    const itemMatch = cart.find((cartItem) => cartItem.name === item.name);
    // if item found increase amount by 1
    if (itemMatch !== undefined) {
        itemMatch.amount = itemMatch.amount + 1;
    } else { // if item not found add that item to array
        
        cart.push(item);
    }
    // and returning it
    return [...cart];
})

// output
/* [
    { name: 'ab', amount: 15 },
    { name: 'def', amount: 10 },
    { name: 'abc', amount: 5 }
] */

In Scenario 2:

const setCart = ((cart) => {
    //  looping into the cart array and searching if item exist in cart or not
    const updatedCart = cart.map((cartItem) => {
        // if item which are in cart is also exist
        if (cartItem.name === item.name) {
            // return all oder cart item, and update the amount 
            return {...cartItem, amount: cartItem.amount + item.amount }
        } else {
            // return the cart item as it is
            return cartItem
        }
    })

    // returning the cart array
    return updatedCart;
})

// output
/* [
    { name: 'ab', amount: 15 },
    { name: 'def', amount: 10 }
] */

In Scenario 2,

you can never be able to add a new item into cart, because you're looping into cart item and checking if item exist or not (if exist update the cart, and if not exist just return the cart item as it is).

In Scenario 1,

you're first finding if the cart item is exist or not, and ensure if the item is already exist in cart just update the amount, and if not exist then add item to cart. (This works in real Scenario)

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