254

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 9

457
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
    });
}
Sign up to request clarification or add additional context in comments.

6 Comments

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 :)
@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 youtube.com/watch?v=mHtdZgou0qU
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.
Why arr becomes an object? Does js can has array of objects like array, not like object? jsfiddle.net/91cgc4zu
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.
|
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.

5 Comments

+1 since the key solution, makes more sense and help me with my needs:)
it looks like you are missing a semi-colon after you set the var key?
nice answer, been looking for how to access the information for a while, thank you
what if key need to be more than once ! ['notes'] can occur more than once then what can we do?
Milson - in that case, it's not really a "key"
41

You can do something like that in ES6.

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

Comments

22

This is what Array#map are good at

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

Comments

5

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 }));

Comments

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});
  }

Comments

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)));
}

Comments

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};
}

Comments

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});
}

2 Comments

It's better to init an array using [] instead of new Array().
Interesting discussion [] vs. new Array() stackoverflow.com/questions/7375120/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.