Andrew Andrew - 2 years ago 56
Javascript Question

Easiest way to fill array with an object in JavaScript without coding a loop?

Say I have the following object:

var obj = { foo: 'bar' };

I want to add this object to an array X amount of times so the result is:

[{ foo: 'bar' }, { foo: 'bar'}, ... , { foo: 'bar'}]

Is there a way to accomplish this without explicitly coding a loop?

Answer Source

You can use map

var filled = Array.apply(null, Array(501)).map(function() { return {"foo":"bar"} });
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download