I'm trying to fill an array with new objects, but the only thing I get is - Uncaught TypeError: product is not a constructor
Here's my code for obj. constructor:
function product(id, preview, colors, sizes, title, price) {
this.id = id;
this.preview = preview;
this.colors = colors;
this.sizes = sizes;
this.title = title;
this.price = price;
};
and code for loop:
var products = [];
for( i=0; i<db.length; i++) {
var xyz = db[i];
products[i] = new product( xyz.id, xyz.preview, xyz.colors, xyz.sizes, xyz.title, xyz.price );
};
here's "minfied" code block example:
https://jsfiddle.net/cujrfhyL/1/
-Thanks in advance.
If products array variable already has some kind of data, it's better you use the array push as not to override the data it contains
var product1 = { id: 6566, price: 3 };
var product2 = { id: 6566, price: 3 };
var product3 = { id: 6568, price: 3 };
var db = [ product1, product2 ];
function product(id, price) {
this.id = id;
this.price = price;
};
var products = [new product(product3.id,product3.price)];
function addProducts() {
for( i=0; i<db.length; i++) {
var xyz = db[i];
products.push(new product( xyz.id, xyz.price ));
}
console.log(products)
};
addProducts();
You need to use the new operator.
products[i] = new product( xyz.id, xyz.price );
var product1 = { id: 6566, price: 3 };
var product2 = { id: 6566, price: 3 };
var db = [ product1, product2 ];
function product(id, price) {
this.id = id;
this.price = price;
};
var products = [];
function addProducts() {
for( i=0; i<db.length; i++) {
var xyz = db[i];
products[i] = new product( xyz.id, xyz.price );
alert(products[i]);
}
};
addProducts();
Don't know if you are having your same problem on local, but in your fiddle you misstyped:
Written there:
var product1 = { id: 6566, price: 3 };
var product2 = { id: 6566, price: 3 };
var db = [ product6566, product6646 ];
But you need to reference product1 and product2 in db:
var db = [ product1, product2 ];
Appart from that, you need to use the "new" keyword:
your code:
products[i] = product( xyz.id, xyz.price );
Correct code:
products[i] = new product( xyz.id, xyz.price );
In Updated working fiddle you can see it working perfectly
Related
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);
}
}
The variables following are defined through a Car prototype:
var Car = function(maker, type, model) {
this.maker = maker;
this.type = type;
this.model = model;
}
var golf = new Car('VW', 'Hatchback', 'Golf');
var sentra = new Car('Nissan', 'Sedan', 'Sentra');
var _328i = new Car('BMW', 'Convertible', "328i");
var gallardo = new Car('Lamborghini', 'Convertible', "Gallardo");
var corniche = new Car('Rolls Royce', 'Sedan', "Corniche");
Car.prototype.year = 0;
golf.year = 2015;
sentra.year = 2010;
_328i.year = 2019;
gallardo.year = 2020;
corniche.year = 1998;
How does one build an array of the var values for the property maker
Something that might console log like this:
(5) ['VW', 'Nissan', 'BMW', 'Lamborghini', 'Roll Royce']
You could create an array of the car instances and use the map function
console.log(
[golf, sentra, _328i, gallardo, corniche].map((car) => car.maker)
)
There are a lot of solutions to that. First, you need to make an array with all your cars, and then use a method to iterate on each car to get the car maker.
Here two examples:
var Car = function (maker, type, model) {
this.maker = maker;
this.type = type;
this.model = model;
}
Car.prototype.year = 0;
var golf = new Car ('VW', 'Hatchback', 'Golf');
var sentra = new Car ('Nissan', 'Sedan', 'Sentra');
var _328i = new Car ('BMW', 'Convertible', "328i");
var gallardo = new Car ('Lamborghini', 'Convertible', "Gallardo", 2020);
var corniche = new Car('Rolls Royce', 'Sedan', "Corniche");
golf.year = 2015;
sentra.year = 2010;
_328i.year = 2019;
gallardo.year = 2020;
corniche.year = 1998;
var cars = [golf, sentra, _328i, gallardo, corniche]
var carsMakers = []
for(var i = 0; i < cars.length; i++) {
var c = cars[i]
carsMakers.push(c.maker)
}
console.log(carsMakers)
var carsMakers2 = cars.map(function(c) { return c.maker });
console.log(carsMakers2)
Just like the map approach but using Array.prototype.from:
var Car = function (maker, type, model) {
this.maker = maker;
this.type = type;
this.model = model;
}
var golf = new Car ('VW', 'Hatchback', 'Golf');
var sentra = new Car ('Nissan', 'Sedan', 'Sentra');
var _328i = new Car ('BMW', 'Convertible', "328i");
var gallardo = new Car ('Lamborghini', 'Convertible', "Gallardo");
var corniche = new Car('Rolls Royce', 'Sedan', "Corniche");
Car.prototype.year = 0;
golf.year = 2015;
sentra.year = 2010;
_328i.year = 2019;
gallardo.year = 2020;
corniche.year = 1998;
// Solution here
const makersList = Array.from([golf, sentra, _328i, gallardo, corniche], car => car.maker );
// should print an array of makers string names
console.log(makersList);
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);
}
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;
}
}
I'm building an array dynamically in a test angular app. Basically I have a scope function that generates an array of people and returns the array and I have an ng-repeat on the array. The array is not displaying but I'm not getting any errors in the console either, so idk what's up:
am I calling the getPerson function correctly? If there's a better way to do this do let me know.
heres the fiddle as well
$scope.person = {
firstname: "",
lastname: "",
isActive: true,
fullname: function() {
var personobject;
personobject = $scope.person;
return personobject.firstname
+ " "
+ personobject.lastname;
}
};
$scope.people = function() {
var pplArray = [];
var firstnames = ['abdul','mahmud','gasser','ibtihaj','abudi'];
var lastnames = ['ahmad','samrai','badawi','jasim','ahmad'];
var actives = [true,true,false,true,false];
for (var i = 0; i < firstnames.length; i++) {
pplArray[i] = getPerson(firstnames[i], lastnames[i], actives[i]);
}
return pplArray;
};
$scope.getPerson = function(first, last, active) {
var newPerson = $scope.person;
newPerson.firstname = first;
newPerson.lastname = last;
newPerson.isActive = active;
return newPerson;
};
I've updated your fiddle here : https://jsfiddle.net/7j2khgbj/2/
var myapp = angular.module("myapp", []);
myapp.controller('appCont', function($scope) {
var Person = function(){
this.firstname = "";
this.lastname = "";
this.isActive = true;
};
Person.prototype.fullname = function() {
return this.firstname
+ " "
+ this.lastname;
};
var getPerson = function(first, last, active) {
var newPerson = new Person();
newPerson.firstname = first;
newPerson.lastname = last;
newPerson.isActive = active;
return newPerson;
};
$scope.addPerson = function() {
$scope.people.push({
firstname: $scope.person.firstname,
lastname: $scope.person.lastname
});
$scope.person.firstname = '';
$scope.person.lastname = '';
};
$scope.people = (function() {
var pplArray = [];
var firstnames = ['abdul','mahmud','gasser','ibtihaj','abudi'];
var lastnames = ['ahmad','samrai','badawi','jasim','ahmad'];
var actives = [true,true,false,true,false];
for (var i = 0; i < firstnames.length; i++) {
pplArray[i] = getPerson(firstnames[i], lastnames[i], actives[i]);
}
return pplArray;
})();
/*$scope.people = [
{firstname: 'abdul', lastname: 'ahmad'},
{firstname: 'mahmud', lastname: 'samrai'},
{firstname: 'gasser', lastname: 'badawi'},
{firstname: 'ibtihaj', lastname: 'jasim'},
{firstname: 'abudi', lastname: 'ahmad'},
{firstname: 'ahmad', lastname: 'jasim'},
{firstname: 'abdul', lastname: 'samrai'}
];*/
});
Some problems I saw:
1) $scope.people was a function, not an array (so I simply executed it and saved the result)
2) you were always overwriting the person (you need a Person class that creates new instances for the array element, not overwrite the same instance with new data - that way you'll get the same thing in all the array elements)
3) on $scope you should put things that need to be accessible from the view. Helper functions can just be local in the controller (if you don't want them as services, although as services they are reusable)
4) track by on ng-repeat (in case of duplicate keys)