240

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.

Ahmed Ashour
  • 4,462
  • 10
  • 33
  • 49
codecowboy
  • 9,403
  • 18
  • 76
  • 133

9 Answers9

434
var arr = [];
var len = oFullResponse.results.length;
for (var i = 0; i < len; i++) {
    arr.push({
        key: oFullResponse.results[i].label,
        sortable: true,
        resizeable: true
    });
}
user229044
  • 222,134
  • 40
  • 319
  • 330
RaYell
  • 68,096
  • 20
  • 124
  • 150
  • 3
    calculating length only once is probably a good idea, I choose to add a `var obj` to make the code clearer, of course you can skip it, you can write the whole script in one line if you wish :) – RaYell Aug 17 '09 at 20:16
  • 8
    @Triptych - Yes, but it's a property lookup that you execute with each iteration, which isn't free and can be avoided. Micro-optimization? Possibly. Also, it is a "live" value - if you modify the array in the loop, the length will change on successive iterations which could lead to infinity. Give this a watch http://www.youtube.com/watch?v=mHtdZgou0qU – Peter Bailey Aug 17 '09 at 20:32
  • 2
    Yeah, but you're not modifying the array each iteration. If you were, it would be ridiculous to compare against length anyway in most cases. – Kenan Banks Aug 22 '09 at 16:11
  • Why arr becomes an object? Does js can has array of objects like array, not like object? https://jsfiddle.net/91cgc4zu/ – fdrv Mar 16 '16 at 22:57
  • I like the pattern of getting length outside the loop. Even though it may not matter here, it's a good habit to get into for the cases (and other languages) where it does matter. – JR Lawhorne May 30 '16 at 16:11
  • @fdrv Not sure if you still need a reply to this, but where does `arr` “become” an object? It’s always an object to begin with. A JS Array can have any value inside. – Sebastian Simon Mar 09 '22 at 23:15
62

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.

Kenan Banks
  • 198,060
  • 33
  • 151
  • 170
32

You can do something like that in ES6.

new Array(10).fill().map((e,i) => {
   return {idx: i}
});
tetra master
  • 467
  • 7
  • 13
19

This is what Array#map are good at

var arr = oFullResponse.results.map(obj => ({
    key: obj.label,
    sortable: true,
    resizeable: true
}))
Endless
  • 29,359
  • 11
  • 97
  • 120
4

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});
  }
Andrey Korneyev
  • 25,929
  • 15
  • 67
  • 67
Manjunath Raddi
  • 383
  • 5
  • 13
4

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)));
}
quemeful
  • 8,888
  • 4
  • 54
  • 67
JPIyo
  • 75
  • 1
  • 5
3

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};
}
BenM
  • 4,006
  • 3
  • 23
  • 26
3
var myColumnDefs = new Array();

for (var i = 0; i < oFullResponse.results.length; i++) {
    myColumnDefs.push({key:oFullResponse.results[i].label, sortable:true, resizeable:true});
}
Nick Riggs
  • 1,257
  • 6
  • 7
3

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});
Pe Wu
  • 503
  • 4
  • 12