Problem
I’m trying to add a lot of objects manually into a collection. The best I can figure out is to define an object, create an add
method, and call that add
method multiple times in the object’s constructor.
function FieldMap(){
FieldMap.prototype.add=function(listField,formField,fieldType){
this[listField]={
'formField':formField,
'fieldType':fieldType
}
}
this.add('Status','StatusName','select');
this.add('Builder','Build Org','select');
this.add('Route','RouteName','input');
this.add('DocVersion','Doc Version','input');
//... and so on for maybe 20 entries
}
I know that it would be easier to read the data in from a file, but for various reasons, that’s not an option here. Is there a more efficient way to do this?
Solution
Before I answer your question, I want to clean some things up first.
this[listField]={
'formField':formField,
'fieldType':fieldType
}
Whoa. You are creating an entire new property here based on input a caller gave you. Then, you are setting this to a uniformly designed object every time.
- Not good practice
- We can OOP this up.
Every time this method is called, an object is created with a certain “shape” (certain properties, etc.)
For that, we create a new class:
function ListField(name, formField, fieldType) {
... fill in the rest with property setting ...
}
Now our data is more easily help together.
Time to fix the bad practice mentioned above.
Instead of modifying the very structure of the parent object every time add
is called, you should instead push the new ListField
object into an array.
This will keep all the added ListField
objects in one, easy to access place. This all removes all bad practices.
Is there a more efficient way to do this?
Sure.
Considering you know that you are going to be sending in a large amount of ListField
s, then why not let add
take an array?
FieldMap.prototype.add = function(arr) { // use better name
for(var i = 0; i < arr.length; i++) {
this.listFields.push(arr[i]);
}
}
Then, to call, just pass in an array of the various FieldMap
s.
No, this will not making typing more easily (well, it will by a little bit). However, since the data you are providing is arbitrary, then there is no way you can do this with patterns and loops.
However, this will speed up your code. Instead of calling a method 20+ times in a row, you are calling this method a single time and this method is using a loop 20+ times; a much more efficient task.