Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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?

like image 462
Andrew Avatar asked Nov 27 '22 20:11

Andrew


2 Answers

There is a way: manually. Any programmatic solution will indeed use a loop here, which, if you wish to maintain your sanity -- use it.

like image 80
Sterling Archer Avatar answered Nov 30 '22 10:11

Sterling Archer


You can use map

var filled = Array.apply(null, Array(501)).map(function() { return {"foo":"bar"} });
like image 36
epascarello Avatar answered Nov 30 '22 10:11

epascarello