Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

114
Views
Iterar una propiedad de Object en Array que coincida con Query

Estoy trabajando en React y quiero iterar la propiedad 'cantidad' de un objeto en mi matriz 'carrito' en función de si coincide con el elemento que tenía presionado el botón 'iterar'.

Mi solución original fue esta...

 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]; })

Sin embargo, la iteración contaba de dos en dos.

Mi segunda solución fue esta...

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

Esta solución funciona, pero no puedo entender cuál es la diferencia entre estos dos. Si alguien pudiera ayudar a explicar la diferencia, eso realmente me ayudaría a entender. Gracias.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

En la primera solución, inserta elementos en una matriz ya existente que ya tiene todos esos elementos.

offtop : la segunda solución también es mejor en términos de no mutar los datos existentes.

about 4 years ago · Juan Pablo Isaza Report

0

Aquí estás haciendo cosas diferentes.

Supongamos que tiene una entrada de muestra como esta:

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

En el escenario 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 } ] */

En el Escenario 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 } ] */

En el escenario 2 ,

nunca podrá agregar un nuevo artículo al carrito, porque está ingresando al artículo del carrito y verificando si el artículo existe o no (si existe, actualice el carrito, y si no existe, simplemente devuelva el artículo del carrito como está).

En el escenario 1 ,

primero está averiguando si el artículo del carrito existe o no, y asegúrese de que si el artículo ya existe en el carrito, simplemente actualice la cantidad, y si no existe, agregue el artículo al carrito. (Esto funciona en escenario real)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!