1

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!

3 Answers3

3

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

Demonstration

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
  • `objects = []` would be enough instead of `objects = new Array(len)`. – kapa Feb 21 '14 at 16:11
  • @kapa correct, but I believe setting an initial capacity is slightly more efficient. – p.s.w.g Feb 21 '14 at 16:12
  • @pswg [Depends on the browser](http://jsperf.com/big-array-initialize/2), AFAIK. And microoptimization is evil ;). But I am always ready to learn. – kapa Feb 21 '14 at 16:17
  • @kapa I believe it also depends a lot on the size of the array. See this [comparison](http://jsperf.com/big-array-initialize/8) which has an initial size of 99999, just one less. – p.s.w.g Feb 21 '14 at 16:30
  • @pswg Currently only has data from Chrome :). But of course the size of the array matters. And a lot of other things. I still say do not microoptimize. – kapa Feb 21 '14 at 16:34
0

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]));
htatche
  • 693
  • 3
  • 17
0

One liner using Underscore.js (zip, map and object):

var people = _.map(_.zip(names, lasts, ages), function(p) { return _.object(['name','last','age'], p); });
VH-NZZ
  • 5,248
  • 4
  • 31
  • 47
  • **Note**: if you're new to JS but not to programming in general, I'd highly advise using Underscore. Also, if you don't have Underscore or would like to see an implementation of `_.object()`, have a look at http://stackoverflow.com/a/14399998/2882550 – VH-NZZ Feb 21 '14 at 17:24
  • **Also**: this can be of interest: http://stackoverflow.com/questions/1117916/merge-keys-array-and-values-array-into-an-object-in-javascript – VH-NZZ Feb 21 '14 at 17:33