how to add multiple items to an object in javascript - javascript

im writting a ShoppingCart class to add and remove items from the cart
code is meant to add and remove items from the shopping cart.
class ShoppingCart{
constructor(){
this.total = 0;
this.items = {};
}
addItems(itemName, quantity, price){
this.itemName = itemName;
this.quantity = quantity;
this.price = price;
this.cost = this.quantity * this.price;
this.total += this.cost;
this.items['itemName'] = this.itemName;
this.items['quantity'] = this.quantity;
}
removeItems(itemName, quantity, price){
this.itemName = itemName;
this.quantity = quantity;
this.price = price;
this.cost = this.quantity * this.price;
this.total -= this.cost;
delete this.items['itemName', 'quantity'];
}
}

Basically you need how to add and remove list items.
follow below approach and let me know if it works for you.
<ul id="todo"></ul>
<button onclick="addItemTodo('test')">Add</button>
js
function addItemTodo(text) {
list = document.getElementById("todo");
item = document.createElement('li');
item.innerText = text;
trash = document.createElement('button');
trash.classList.add('btn1');
trash.addEventListener("click", removeActivity);
icon_trash = document.createElement('i');
icon_trash.classList.add('fas', 'fa-trash-alt', 'fa-2x');
item.appendChild(trash);
trash.appendChild(icon_trash);
list.appendChild(item); }
function removeActivity() {
var listItems = document.getElementsByTagName("li");
for (var i = 0; i < listItems.length; i++) {
listItems[i].onclick = function() {
this.parentNode.removeChild(this);
}
}
}
Live demo

Related

Add same object to an array

I've created a shopping cart, and right now the the cart contains a single apple, a single orange, and the total prices.
How would I add a second "apple" without creating another object?
For example, I now would like to add 2 apples to the cart, so the price in the array gets updated, as well as the total amount.
module.exports = {
shoppingCart: function () {
//create empty cart array
theCart = [];
// create two seperate versions of the same kind of object using class method
class Fruits {
constructor(fruit, price) {
this.fruit = fruit;
this.price = price;
// this.quantity = price * 2;
}
}
let fruit1 = new Fruits('Apple', 4.95); // create new object. sets the value of this
let fruit2 = new Fruits('Orange', 3.99);
let fruit3 = new Fruits('Total amount', fruit1.price + fruit2.price);
// combine both fruits into an array
let bothFruits = [fruit1, fruit2, fruit3];
//add items to the cart
Array.prototype.push.apply(theCart, bothFruits);
//remove items from the cart by calling this function
function removeAllItems() {
if ((theCart.length = !0)) {
theCart = [];
}
}
//removeAllItems();
console.log(theCart);
},
};
You may try to add the quantity also. Please try the following code:
module.exports = {
shoppingCart: function () {
//create empty cart array
theCart = [];
// create two seperate versions of the same kind of object using class method
class Fruits {
constructor(fruit, price, quantity) {
this.fruit = fruit;
this.quantity = quantity;
this.price = price * quantity;
}
}
let fruit1 = new Fruits("Apple", 4.95, 2); // create new object. sets the value of this
let fruit2 = new Fruits("Orange", 3.99, 1);
let fruit3 = new Fruits("Total amount", fruit1.price + fruit2.price);
// combine both fruits into an array
let bothFruits = [fruit1, fruit2, fruit3];
//add items to the cart
Array.prototype.push.apply(theCart, bothFruits);
//remove items from the cart by calling this function
function removeAllItems() {
if (theCart.length = !0) {
theCart = [];
}
}
//removeAllItems();
console.log(theCart);
}
}
You can try this code:
class Fruits {
constructor() {
this.items = [];
this.totals = 0;
}
calculateTotals() {
this.totals = 0;
this.items.forEach(item => {
let price = item.price;
let quantity = item.quantity;
let amount = price * quantity;
this.totals += amount;
});
}
addToCart(fruit, price, quantity) {
let obj = { fruit, price, quantity }
this.items.push(obj);
this.calculateTotals();
}
get cart() {
return { items: this.items, totals: this.totals }
}
}
const fruitsCart = new Fruits();
fruitsCart.addToCart("Apple", 10.5, 2);
fruitsCart.addToCart("Orang", 15, 1);
const cart = fruitsCart.cart;
this now adds the total amount in a separate variable
module.exports = {
shoppingCart: function () {
//create empty cart array
theCart = [];
// create two seperate versions of the same kind of object using class method
class Fruits {
constructor(fruit, price, quantity) {
this.fruit = fruit;
this.quantity = quantity;
this.price = price * quantity;
}
}
let fruit1 = new Fruits("Apple", 4.95, 2); // create new object. sets the value of this
let fruit2 = new Fruits("Orange", 3.99, 1);
//let fruit3 = new Fruits("Total amount", fruit1.price * fruit2.price);
// combine both fruits into an array
let bothFruits = [fruit1, fruit2];
//add items to the cart
Array.prototype.push.apply(theCart, bothFruits);
let total = fruit1.price + fruit2.price;
//remove items from the cart by calling this function
function removeAllItems() {
if (theCart.length = !0) {
theCart = [];
}
}
//removeAllItems();
console.log(theCart, total);
}
}

How to remove items from an array on a checkout page

New to JS and trying to create a simple shopping cart using only vanilla JS. I have an item with details and an image that populates on a shopping cart page. I need to have a delete button that allows items to be removed individually from the shopping cart page. Below is the snippet of code I'm having trouble with:
function deleteProduct(i) {
alert('i : ' + i)
productArr2.splice(i,1)
console.log(productArr2)}
And below is the full JS code in case it would be helpful for debugging. Any help is appreciated!:
//Global Variables
var quantity = "";
var glazes = "";
var img = "";
var addItem = "";
//Changes price when quantity is selected
function priceCounter(){
var price = document.getElementById("price-details");
price.innerHTML = document.getElementById("quantity").value;
}
function setImage(select){
var image = document.getElementsByName("image-swap")[0];
image.src = select.options[select.selectedIndex].value;
}
function items(title, quantity, glaze, price, img){
this.title = title;
this.quantity = quantity;
this.glaze = glaze;
this.price = price;
this.img = img;
}
//Add to Cart Functionality
function addToCart() {
var quantityCount = document.getElementById("quantityCount");
quantityCount.innerText = document.getElementById("quantity").value;
document.getElementById("quantityCount").style.visibility = "visible";
title = document.getElementsByClassName("productTitle");
quantity = document.getElementById("quantity").value;
glazing = document.getElementById("glazing").value;
price = document.getElementById("quantity").value;
img = "images/blackberry-bag.png"
addItem = new items(title, quantity, glazing, price, img);
window.localStorage.setItem(localStorageCount, JSON.stringify(addItem));
// localStorageCount += 1;
}
//creates array to hold bag items
var productArr = []
var productArr2 = []
class Product {
constructor(quantity, glaze) {
this.quantity = quantity
this.glaze = glaze
}
}
function addToCart() {
var quantity = document.getElementById('quantity').value
var glaze = document.getElementById('glaze').value
var bun = new Product(quantity, glaze)
productArr.push(bun)
updateCartNumber(productArr.length)
}
function goToCheckoutPage() {
alert("taking you to your cart")
localStorage.setItem('order', JSON.stringify(productArr))
window.location.replace("cart.html")
}
function checkoutPageLoaded() {
var loadedProductArr = localStorage.getItem('order')
var productArr2 = JSON.parse(loadedProductArr)
console.log(productArr2)
var cart = document.getElementById("cart")
for(var i = 0; i < productArr2.length; i++) {
var cinbun = productArr2[i]
var cinbunGlaze = cinbun.glaze
var cinbunQuantity = cinbun.quantity
cart.innerHTML += "<div class='cart-items'> Flavor: Pumpkin Spice Glaze: <img src="+ cinbunGlaze +"> Price: "+ cinbunQuantity +"</div>"
cart.innerHTML += "<span onclick= 'deleteProduct(" + i + ")'> Delete </span>"
}
}
function saveEdits() {
localStorage.setItem('order', JSON.stringify(productArr2))
}
function deleteProduct(i) {
alert('i : ' + i)
productArr2.splice(i,1)
console.log(productArr2)
}
function updateCartNumber(num) {
var cartCount = document.getElementById('quantityCount')
cartCount.innerHTML = num
}

Shopping cart using OO javascript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I am trying to create a simple shopping cart using javascript and prototypes.
Just a simple console app.
I want to call myBasket.prototype.addItems to add items in the inventory[] and similarly I would want to call myBasket.prototype.addQuantity and myBasket.prototype.totalAmount to increase the quantity of an item and sum the total amount respectively.
Where I am stuck is how do I call myBasket.prototype.addItems to do the needful? This is where I am stuck.
var inventory =
[
{ name: "apples", price: 19.95, quantity: 50 },
{ name: "oranges", price: 20.99, quantity: 40 },
{ name: "pineapples", price: 40.00, quantity: 60 },
{ name: "lemons", price: 10.12, quantity: 100 }
]
function myBasket(name, price, quantity){
this.name = name;
this.price = price,
this.quantity = quantity;
items.push(this);
}
myBasket.prototype.addItems = function(){
console.log('items added to cart')
}
myBasket.prototype.addQuantity = function(){
console.log('item quantity added to cart')
}
myBasket.prototype.totalAmount = function(){
console.log('Total amount is');
var total = this.price * this.quantity;
}
// newItem.prototype = Object.create(myBasket.prototype);
var newItem = [];
newItem = new myBasket({name:'milk', price:80,quantity: 2});
newItem.push(this.items);
console.log('new item(s) added', items);
var checkoutAmount = new myBasket();
console.log('checkout amount');
No, since you are new to OOP, think it this way. Every thing is an object.
So in your case, you should have class Item and class Basket you should also have a way to add and remove items from your basket.
See the code snippet bellow
class Item{
constructor(name,price,quantity) {
this.name = name;
this.price = price;
this.quantity = quantity;
}
}
class Basket {
constructor() {
this.items = []
}
addItem(item){
this.items.push(item)
}
}
let items = [
new Item("apples",40,20),
new Item("lemons",32,38),
new Item("mangos",44,67),
new Item("pineapples",32,88)
]
let basket = new Basket()
let market = document.getElementById("market")
let s = items.map((item,id)=>"<button onClick=addItem("+id+")>Add "+item.name+"</button>").join("")
market.innerHTML = s
function addItem(id) {
basket.addItem(items[id])
showBasket()
}
function showBasket() {
let cart = document.getElementById("items")
let s = basket.items.map((item,id)=>"<span style='margin: 5px'>"+item.name+"</span>").join("")
cart.innerHTML = s
}
<fieldset>
<legend>Basket</legend>
<div id="items"></div>
</fieldset>
<div id="market"></div>
Hope that answers your question
Since the question was edited and added to use prototypes, I am going to once more produce an elaboration using function prototypes
function Item(name,price,quantity) {
this.name = name;
this.price = price;
this.quantity = quantity;
}
function Basket() {
this.items = []
}
Basket.prototype.addItem = function(item) {
this.items.push(item);
}
let items = [
new Item("apples",40,20),
new Item("lemons",32,38),
new Item("mangos",44,67),
new Item("pineapples",32,88)
]
let basket = new Basket()
let market = document.getElementById("market")
let s = items.map((item,id)=>"<button onClick=addItem("+id+")>Add "+item.name+"</button>").join("")
market.innerHTML = s
function addItem(id) {
basket.addItem(items[id])
showBasket()
}
function showBasket() {
let cart = document.getElementById("items")
let s = basket.items.map((item,id)=>"<span style='margin: 5px'>"+item.name+"</span>").join("")
cart.innerHTML = s
}
<fieldset>
<legend>Basket</legend>
<div id=items></div>
</fieldset>
<div id=market></div>
To add items to an array, use push():
function myBasket(name, price, quantity){
this.name = name;
this.price = price,
this.quantity = quantity;
items.push(this);
}

Add method to Constructor function that manipulates an Array

I am attempting to create a simple program for practice that has a Store constructor which takes in an inventoryList array, an InventoryItem constructor that creates an object of each item to be stored within the inventoryList array. I want to add a method to the InventoryItem list that will take a number and add it to each item within the list. Below is my code:
var Store = function(inventory){
this.inventory = inventory;
}
var InventoryItem = function(cost, color, size){
this.cost = cost;
this.color = color;
this.size = size;
}
//create each inventory item as an object
var lamp = new InventoryItem(40.00, 'blue', 'small');
var throwPillow = new InventoryItem(25.00, 'yellow', 'medium');
var sconce = new InventoryItem( 18.00, 'gold', 'large');
var candles = new InventoryItem(10.00, 'white', 'small');
var curtains = new InventoryItem(30.00, 'purple', 'large');
//store inventory items into an inventory object
var inventorylist = [lamp, throwPillow, sconce, candles, curtains];
// add number of items to each item
InventoryItem.prototype.howMany = function(num){
function addCount(inventorylist){
for(var i = 0; i < inventorylist.length; i++){
inventorylist[i].howMany = num;
}
}
}
//store inventory within a store
var deannaStore = new Store(inventorylist);
var dionStore = new Store(inventorylist);
var mikeStore = new Store(inventorylist);
I am running into an issue when I attempt add a number to an item within the list
example: dionStore.howMany(15)
this gives me the error: Uncaught TypeError: dionStore.howMany is not a function
Any help would be greatly appreciated preferably with a detailed explanation of why this doesn't work.
The problem is that the method howMany is defined for InventoryItem objects, but you try to call it to dionStore object which is a Store.
Can you please describe what you want to achieve?
EDIT1 :
Maybe add the howMany method to Store, like Lashane mentions, which will create a quantity property to each InvetoryItem in its array
Store.prototype.howMany = function(num){
function addCount(inventorylist){
for(var i = 0; i < inventorylist.length; i++){
inventorylist[i].quantity = num;
}
}
}
EDIT2 :
In this case you will need a method in InventoryItem to set the quantity and another in Store to return the total quantity
Store.prototype.howMany = function(){
var totalQuantity = 0;
for(var i = 0; i < inventorylist.length; i++){
var item = inventorylist[i];
if (item.hasOwnProperty('quantity')) {
totalQuantity += item.quantity;
}
}
return totalQuantity;
}
InventoryItem.prototype.addQuantity = function(quantity) {
if (this.hasOwnProperty('quantity')) {
this.quantity += quantity;
} else {
this.quantity = quantity;
}
}
var Store = function(inventory) {
this.inventory = inventory;
}
Store.prototype.howMany = function() {
var totalQuantity = 0;
for (var i = 0; i < inventorylist.length; i++) {
var item = inventorylist[i];
if (item.hasOwnProperty('quantity')) {
totalQuantity += item.quantity;
}
}
return totalQuantity;
}
var InventoryItem = function(cost, color, size) {
this.cost = cost;
this.color = color;
this.size = size;
}
InventoryItem.prototype.addQuantity = function(qunatity) {
if (this.hasOwnProperty('quantity')) {
this.quantity += qunatity;
} else {
this.quantity = qunatity;
}
}
//create each inventory item as an object
var lamp = new InventoryItem(40.00, 'blue', 'small');
var throwPillow = new InventoryItem(25.00, 'yellow', 'medium');
var sconce = new InventoryItem(18.00, 'gold', 'large');
var candles = new InventoryItem(10.00, 'white', 'small');
var curtains = new InventoryItem(30.00, 'purple', 'large');
//store inventory items into an inventory object
var inventorylist = [lamp, throwPillow, sconce, candles, curtains];
lamp.addQuantity(1);
throwPillow.addQuantity(2);
sconce.addQuantity(3);
candles.addQuantity(4);
curtains.addQuantity(5);
lamp.addQuantity(1);
//store inventory within a store
var deannaStore = new Store(inventorylist);
var dionStore = new Store(inventorylist);
var mikeStore = new Store(inventorylist);
document.getElementById('output').innerHTML = 'dionStore.howMany() = ' + dionStore.howMany();
<div id="output"></div>
Your prototype defines a function and does nothing. And it is on the wrong prototype. Are you looking for this?
Store.prototype.howMany = function(num){
for(var i = 0; i < this.inventory.length; i++){
this.inventory[i].howMany = num;
}
}

for var in key loop displaying the same property instead of 4 different ones

Im trying to make an addressbook in javascript and the issue I have is that the properties of my objects are not giving me the info I need. I want 4 different property and not 4 loops of same property.
The for loop is makes a loop of 4 lis list items thats gonna be inserted from the info I have in the objects.
But instead I got EMAIL all the loops.
Hope you understand and can help me.
Here is the code.
//Contactlist funktion
function Contact(fname, lname, address, email) {
this.fname = fname;
this.lname = lname;
this.address = address;
this.email = email;
}
// Contacts
var tony = new Contact("Tony", "Stark", "Avengers 123", "i.am.ironman#hotmail.com");
var steve = new Contact("Steve", "Rogers", "Avengers 12", "cap.america#hotmail.com");
//All contacts
var contacts = [tony, steve];
// Appending the objects
var body = document.getElementsByTagName('body')[0];
var ul = document.createElement('ul');
body.appendChild(ul);
function theContacts() {
var li = document.createElement('li');
li.innerHTML = tony.fname + ' ' + stark.lname;
ul.appendChild(li);
for (i = 0; i < 4; i++) {
li = document.createElement('li');
for (var key in tony) {
li.innerHTML = key;
}
ul.appendChild(li);
}
}
// Calling the object
theContacts();
Thanks for your help!
This will output all contacts with their properties as nested unordered lists. I have given classnames to the elements for easy styling. Start just below your var contacts.
function theContacts() {
var body = document.getElementsByTagName('body')[0],
outerUL = document.createElement('ul'),
length = contacts.length;
outerUL.className = 'contactlist';
for (var i = 0; i < length; i++) {
var cont = contacts[i],
li = document.createElement('li'),
ul = document.createElement('ul');
li.className = 'contact'; li.innerHTML = cont.fname + ' ' + cont.lname;
ul.className = 'infos';
for (var key in cont) {
var info = document.createElement('li');
info.className = key;
info.innerHTML = cont[key];
ul.appendChild(info);
}
li.appendChild(ul); outerUL.appendChild(li);
}
body.appendChild(outerUL);
}
The problem you had results from confusion with var li inside theContacts().

Categories