m aksem
m aksem

Reputation: 571

Populating array with new objects inside a loop

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.

Upvotes: 0

Views: 96

Answers (3)

ayinloya
ayinloya

Reputation: 134

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();

Upvotes: 2

Mayday
Mayday

Reputation: 5136

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

Upvotes: 0

Abhinav Galodha
Abhinav Galodha

Reputation: 9878

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();

Upvotes: 1

Related Questions