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

后端 未结 9 1636
一整个雨季
一整个雨季 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 04:18

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

    This is what Array#map are good at

    var arr = oFullResponse.results.map(obj => ({
        key: obj.label,
        sortable: true,
        resizeable: true
    }))
    
    0 讨论(0)
  • 2020-12-02 04:20

    If you want to go even further than @tetra with ES6 you can use the Object spread syntax and do something like this:

    let john = {
        firstName: "John",
        lastName: "Doe",
    };
    
    let people = new Array(10).fill().map((e, i) => {(...john, id: i});
    
    0 讨论(0)
提交回复
热议问题