I know I can init an array of JS objects like this:
var things = [
{
prop1: 'foo',
prop2: 'bar'
},
{
prop1: 'foo',
prop2: 'bar'
}
];
I guess I would call these 'anonymous' types (sorry, I'm using C#/.NET language).
What if I want these to be of the same prototype? So I have defined a constructor:
var Thing = function Thing() {
};
Thing.prototype.prop1 = 'default value';
Thing.prototype.prop2 = 'default value';
Now I want both the items in my original code above to be Thing
s. Is there a good way to do this?
If I were to guess, I would say maybe something like:
var things = [
new Thing() {
prop1: 'foo',
prop2: 'bar'
},
new Thing() {
prop1: 'foo',
prop2: 'bar'
}
];
Which is basically C# object initializer syntax. What I'm trying to avoid is:
var thing1 = new Thing();
thing1.prop1 = 'foo';
thing1.prop2 = 'bar';
var thing2 = new Thing();
thing2.prop1 = 'foo';
thing2.prop2 = 'bar';
var things = [thing1, thing2];
Edit:
I should also note that my prototypes also contain some functions that are shared. Also in actuality I have arrays nested 3 deep, so its something more like:
{
[
{
[
{},
{}
]
},
{
[
{},
{}
]
}
]
}
Which is why I as hoping to just init everything inline like this and not setting each property line by line.
You can initialize an array with Array constructor syntax using new keyword. The Array constructor has following three forms. Syntax: var arrayName = new Array(); var arrayName = new Array(Number length); var arrayName = new Array(element1, element2, element3,...
We can use the forEach method to loop through each element in an object and add a property to each. We have the arr array. Then we call forEach with a callback that has the element parameter with the object being iterated through and we assign the b property to a value.
Creating an array of objectsWe can represent it as an array this way: let cars = [ { "color": "purple", "type": "minivan", "registration": new Date('2017-01-03'), "capacity": 7 }, { "color": "red", "type": "station wagon", "registration": new Date('2018-03-03'), "capacity": 5 }, { ... }, ... ]
var Thing = function(params) {
this.prop1 = params.prop1;
this.prop2 = params.prop2;
};
var things = [
new Thing({
prop1: 'foo',
prop2: 'bar'
}),
new Thing({
prop1: 'foo',
prop2: 'bar'
}),
];
You are not making use of your 'constructor'. Its preferred to initialize values IN YOUR CONSTRUCTOR:
var Thing = function Thing(prop1, prop2) {
this.prop1 = prop1;
this.prop2 = prop2;
};
and then do:
var thing1 = new Thing("foo", "bar");
var thing2 = new Thing("foo", "bar");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With