Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an array in javascript of custom objects

Tags:

javascript

Hi I need some help with javascript.

function PricingData(id,method,freq,service,price) {
            this.ID=id;
            this.PaymentMethod_ID=method;
            this.PaymentFrequency_ID=freq;
            this.Service_ID=service;
            this.Price=price;
        }

I need to create an array in this way.

var temp=new PricingData[]{new PricingData(1,2,3,4,5),new PricingData(1,2,3,4,5)};

but this doesn't work. I'm going to pass the data in through the server so I would prefer syntax similar to this

like image 613
David Avatar asked Feb 25 '11 09:02

David


People also ask

How do you turn an object into an array in JavaScript?

To convert an object to an array you use one of three methods: Object. keys() , Object. values() , and Object. entries() .

Can you have an array of objects in JavaScript?

JavaScript variables can be objects. Arrays are special kinds of objects. Because of this, you can have variables of different types in the same Array.

What is {} and [] in JavaScript?

{} is shorthand for creating an empty object. You can consider this as the base for other object types. Object provides the last link in the prototype chain that can be used by all other objects, such as an Array . [] is shorthand for creating an empty array.


2 Answers

Use array literal notation to create an array:

var tmp = [new PricingData(1,2,3,4,5), new PricingData(1,2,3,4,5)];

For more information about arrays have a look at MDC - Array.

like image 150
Felix Kling Avatar answered Nov 01 '22 08:11

Felix Kling


just put the new object right between the square brakcets

var arr = [new whatever(), new whatever()];
like image 37
Ollie Edwards Avatar answered Nov 01 '22 09:11

Ollie Edwards