Reputation: 15
I have several arrays with stored information from a simple form
var name = [a, b, c, ...];
var last = [x, y, z, ...];
var age = [1, 2, 3];
Now it is the idea that when someone new fills in the form, and thus a new element is added to the arrays, a new object is created which holds this persons information like:
function Person(name,last,age){
this.name=name;
this.last=last;
this.age=age;
}
var object1 = new Person(name[1],last[1],age[1]);
Obviously I don't want to manually create a new object every time, so I guess something has to be done with a for loop, but how does this generate a new name for object(i)?
I am quite new to javascript, and possibly I am overthinking things and is the answer staring me right in the face, But I really could use some help here. Thanks a million!
Upvotes: 1
Views: 108
Reputation: 5428
One liner using Underscore.js (zip, map and object):
var people = _.map(_.zip(names, lasts, ages), function(p) { return _.object(['name','last','age'], p); });
Upvotes: 0
Reputation: 693
Slightly different version from p.s.w.g which is good anyways, assuming that every field is always filled (every array has the same size).
var persons = [];
for (var i = 0; i < names.length; i++)
persons.push(new Person(names[i], lasts[i], ages[i]));
Upvotes: 0
Reputation: 149000
How about something like this:
var len = Math.min(name.length, last.length, age.length),
objects = new Array(len);
for (var i = 0; i < len; i++)
objects[i] = new Person(name[i], last[i], age[i]);
Upvotes: 3