views:

946

answers:

4

Hi,

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.

thanks,

codecowboy.

+7  A: 
var arr = [];
var len = oFullResponse.results.length;
for (var i = 0; i < len; i++) {
    var obj = {
        key: oFullResponse.results[i].label,
        sortable: true,
        resizeable: true
    };
    arr.push(obj);
}
RaYell
Would upvote if not for SO's restrictions.
mcandre
you can skip the `var obj = {` bit, just push the literal itself.
Peter Bailey
I would calculate `length` only once.
kangax
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
@kangax, Length isn't "calculated", it's an O(1) operation.
Triptych
thanks all. Lightning response!
codecowboy
@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
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.
Triptych
A: 

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
+1  A: 
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
It's better to init an array using `[]` instead of `new Array()`.
RaYell
A: 

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.

Triptych