Easiest way to populate an array with an object in JavaScript without loop encoding?

Let's say I have the following object:

var obj = { foo: 'bar' };

I want to add this object to array X a number of times so that the result:

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

Is there a way to do this without explicitly encoding the loop?

+4
source share
7 answers

You can use map

var filled = Array.apply(null, Array(501)).map(function() { return {"foo":"bar"} });
+6
source

There is a way: manually. Any software solution will really use a cycle here, which, if you want to maintain your sanity, use it.

+11
source

, .fill

const someArray = ['test']; // Any other data you may have
const resultingArray = new Array(100).fill({ foo: 'bar' }).concat(someArray);

100 , , concat ( , )

@isvforall, , , . , .

+4

, epascarello , +1, , Array.join() JSON.stringify() JSON.parse().

:

var obj = { foo: 'bar' };
var objJSON = JSON.stringify(obj);
var list = new Array(501).join(objJSON + ',')
var trimmedList = list.substr(0, list.length - 1); // getting rid of that last comma
var arrayJSON = '[' + trimmedList + ']';
var array = JSON.parse(arrayJSON);
console.log(array);

:

var list = new Array(501).join(JSON.stringify({ foo: 'bar' }) + ',')
var array = JSON.parse('[' + list.substr(0, list.length - 1) + ']');
console.log(array);
+2

, .

function objFillArray(obj, count) {
    let ret = [];
    return notALoop();
    function notALoop() {
        ret.push(obj);
        if( --count ) return notALoop();
        return ret;
    }
}

notALoop count .

+2

concat

var obj = { foo: 'bar' };

var result = (function fill(a, len) {
    return a.length == len ? a : fill(a.concat(obj), len);
})([], 10);

var obj = { foo: 'bar' };

var result = (function fill(a, len) {
    return a.length == len ? a : fill(a.concat(obj), len);
})([], 10);

document.write(JSON.stringify(result));
Hide result
+1
source

Use a function .push()to assign a value to an array.

    yourarray.push(yourobject);
               |
               |
               |
               V
    fiveHundredChars.push(obj);
-1
source

All Articles