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

232
Views
Tener un duplicado de un objeto, o como multiplicarlo

Tengo un carrito de compras con una manzana y un objeto naranja. Quiero poder agregar la manzana dos veces, pero no estoy seguro de cómo apuntar dos veces al objeto "fruta1" para mostrar 2 manzanas en el carrito. Básicamente, quiero actualizar la matriz del carrito con "2 manzanas", con el "valor" del precio duplicado y 1 naranja)

 module.exports = { shoppingCart: function () { //create empty cart array theCart = []; // all fruits let fruitProducts = [ { fruit1: 'Apple', price: 4.95, }, { fruit2: 'Orange', price: 3.99, }, ]; //push the objects into the empty array using the apply method -- add items to the cart Array.prototype.push.apply(theCart, fruitProducts); //remove items from the cart by calling this function function removeAllItems() { if ((theCart.length = !0)) { theCart = []; } } //removeAllItems(); console.log(theCart); }, };
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Parece que está preguntando cómo encontrar un objeto de una matriz y luego copiarlo.

Primero, para encontrar fruit1:

 const apple = fruitProducts.find(fruit => “fruit1” in fruit);

Luego, para enviar copias de ese objeto a su carrito, puede usar el operador de extensión para hacer una copia superficial:

 theCart.push(…apple); theCart.push(…apple);

Dicho esto, una mejor solución es mantener una lista de objetos cuyas propiedades son fruta, cantidad y precio. Luego, puede calcular el precio total una vez que haya terminado de agregar artículos al carrito.

about 4 years ago · Juan Pablo Isaza Report

0

Utilice .map() . Agregue la qty de propiedad y total y pase una extensión de números ( ...amounts ej. 1, 2, 5 ) que representan las cantidades de cada artículo.

 const fruit = [{ "fruit": "Apple", "price": 4.95 },{ "fruit": "Orange", "price": 3.99 } ]; const shop = (product, ...amounts) => { let qty = [...amounts] || []; let cart = product.map((item, count) => { item.qty = qty[count] || 0; item.total = parseFloat((item.qty * item.price).toFixed(2)); return item; }); return cart; }; console.log(shop(fruit, 1, 3)); console.log(shop(fruit, 4)); console.log(shop(fruit)); console.log(shop(fruit, 1, 3, 2));

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!