[removed] convert two dimensional array to array of objects using the first 'row' to define properties

前端 未结 7 1284
南方客
南方客 2020-12-03 16:33

In order to populate a data-grid that receives array of row objects, I am looking for a good solution to convert an array such as this:

[  
[\'country\', \'p         


        
7条回答
  •  不思量自难忘°
    2020-12-03 17:03

    Using a combination of map and forEach you can map the subsequent array elements to the columns specified in the first element.

    var arr = [  
       ['country', 'population'],
       ['someplace', 100],
       ['otherplace', 200]
    ];
    
    var cols = arr.shift();
    newArr = arr.map(function(element,index){
       var newObj = {};
       element.forEach(function(data,index){
          newObj[cols[index]]=data;
       });
       return newObj;
    });
    

提交回复
热议问题