251

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
  • 5,179
  • 10
  • 35
  • 56
codecowboy
  • 9,835
  • 18
  • 79
  • 134

9 Answers9

451
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
  • 232,980
  • 40
  • 330
  • 338
RaYell
  • 69,610
  • 20
  • 126
  • 152
  • 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
  • 207,056
  • 34
  • 155
  • 173
38

You can do something like that in ES6.

new Array(10).fill().map((e,i) => {
   return {idx: i}
});
tetra master
  • 537
  • 8
  • 13
22

This is what Array#map are good at

var arr = oFullResponse.results.map(obj => ({
    key: obj.label,
    sortable: true,
    resizeable: true
}))
Endless
  • 34,080
  • 13
  • 108
  • 131
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
  • 26,353
  • 15
  • 70
  • 71
Manjunath Raddi
  • 421
  • 6
  • 15
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
  • 9,542
  • 4
  • 60
  • 69
JPIyo
  • 75
  • 1
  • 5
4

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, id) => ({ ...john, id }));
Pe Wu
  • 533
  • 4
  • 12
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,056
  • 3
  • 24
  • 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,267
  • 6
  • 7