How to create an array of object literals in a loop?

Viewed 651491

I need to create an array of object literals like this:

var myColumnDefs = [
    {key:"label", sortable:true, resizeable:true},
    {key:"notes", sortable:true,resizeable:true},......

In a loop like this:

for (var i = 0; i < oFullResponse.results.length; i++) {
    console.log(oFullResponse.results[i].label);
}

The value of key should be results[i].label in each element of the array.

9 Answers

You can do something like that in ES6.

new Array(10).fill().map((e,i) => {
   return {idx: i}
});

This is what Array#map are good at

var arr = oFullResponse.results.map(obj => ({
    key: obj.label,
    sortable: true,
    resizeable: true
}))

If you want to go even further than @tetra with ES6 you can use the Object spread syntax and do something like this:

const john = {
    firstName: "John",
    lastName: "Doe",
};

const people = new Array(10).fill().map((e, i) => {(...john, id: i});
Related