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

后端 未结 9 1635
一整个雨季
一整个雨季 2020-12-02 03:45

I need to create an array of object literals like this:

var myColumnDefs = [
    {key:\"label\", sortable:true, resizeable:true},
    {key:\"notes\", sortabl         


        
相关标签:
9条回答
  • 2020-12-02 03:54

    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.

    0 讨论(0)
  • 2020-12-02 03:56

    You can do something like that in ES6.

    new Array(10).fill().map((e,i) => {
       return {idx: i}
    });
    
    0 讨论(0)
  • 2020-12-02 03:59

    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});
      }
    
    0 讨论(0)
  • 2020-12-02 04:03
    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
        });
    }
    
    0 讨论(0)
  • 2020-12-02 04:10

    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};
    }
    
    0 讨论(0)
  • 2020-12-02 04:15
    var myColumnDefs = new Array();
    
    for (var i = 0; i < oFullResponse.results.length; i++) {
        myColumnDefs.push({key:oFullResponse.results[i].label, sortable:true, resizeable:true});
    }
    
    0 讨论(0)
提交回复
热议问题