I have a shopping cart with an apple and an orange object. I want to be able to add the apple twice, but I'm not sure how to target the "fruit1" object twice, in order to display 2 apples in the cart. I essentially want to update the cart array with "2 apples", with the price "value" doubled, and 1 orange)
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);
},
};
It seems like you are asking how to find an object from an array and then copy it.
First, to find fruit1:
const apple = fruitProducts.find(fruit => “fruit1” in fruit);
Next, to push copies of that object to your cart you can use the spread operator to do a shallow copy:
theCart.push(…apple);
theCart.push(…apple);
That being said, a better solution is to keep a list of objects whose properties are fruit, quantity, and price. Then you can compute total price once you are done adding items to the cart.
Use .map(). Add property qty and total and pass a spread of numbers (...amounts ex. 1, 2, 5) representing the quantities of each item.
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));