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

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.

This question is related to javascript arrays object-literal

The answer is


You can do something like that in ES6.

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

In the same idea of Nick Riggs but I create a constructor, and a push a new object in the array by using it. It avoid the repetition of the keys of the class:

var arr = [];
var columnDefs = function(key, sortable, resizeable){
    this.key = key; 
    this.sortable = sortable; 
    this.resizeable = resizeable;
    };

for (var i = 0; i < len; i++) {
    arr.push((new columnDefs(oFullResponse.results[i].label,true,true)));
}

RaYell's answer is good - it answers your question.

It seems to me though that you should really be creating an object keyed by labels with sub-objects as values:

var columns = {};
for (var i = 0; i < oFullResponse.results.length; i++) {
    var key = oFullResponse.results[i].label;
    columns[key] = {
        sortable: true,
        resizeable: true
    };
}

// Now you can access column info like this. 
columns['notes'].resizeable;

The above approach should be much faster and idiomatic than searching the entire object array for a key for each access.


var myColumnDefs = new Array();

for (var i = 0; i < oFullResponse.results.length; i++) {
    myColumnDefs.push({key:oFullResponse.results[i].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:

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

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

I'd create the array and then append the object literals to it.

var myColumnDefs = [];

for ( var i=0 ; i < oFullResponse.results.length; i++) {

    console.log(oFullResponse.results[i].label);
    myColumnDefs[myColumnDefs.length] = {key:oFullResponse.results[i].label, sortable:true, resizeable:true};
}

This will work:

 var myColumnDefs = new Object();
 for (var i = 0; i < oFullResponse.results.length; i++) {
     myColumnDefs[i] = ({key:oFullResponse.results[i].label, sortable:true, resizeable:true});
  }

This is what Array#map are good at

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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to object-literal

How to fill a Javascript object literal with many static key/value pairs efficiently? JavaScript property access: dot notation vs. brackets? Self-references in object literals / initializers Adding/removing items from a JavaScript object with jQuery Dynamically Add Variable Name Value Pairs to JSON Object How to use a variable for a key in a JavaScript object literal? How to create an array of object literals in a loop? How can I add a key/value pair to a JavaScript object?