Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: convert two dimensional array to array of objects using the first 'row' to define properties

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', 'population'],
['someplace', 100],
['otherplace', 200]
]

into an array of objects such as this:

[
{country: 'someplace', population: 100},
{country: 'otherplace', population: 200},
]

UPDATE:

this is the solution I am using so far:

 function arrayToRows(arr) {
var defs = [];
var data = [];
var rows = [];
var r;
var obj;



var headerRow = arr.shift(); //remove header row

defs = headerRow.map(function(cell) {
  return {
    field: cell,
    displayName: cell
  }
});


for (var i = 0; i < arr.length; i++) {
  r = arr[i];
  obj = {};

  for (var j = 0; j < defs.length; j++) {
    obj[defs[j].field] = r[j];
  }
  rows.push(obj);
}
return rows;

}

like image 270
CodeToad Avatar asked Nov 28 '22 13:11

CodeToad


1 Answers

var array = [  
    ['country', 'population'],
    ['someplace', 100],
    ['otherplace', 200]
];

var keys = array.shift();
var objects = array.map(function(values) {
    return keys.reduce(function(o, k, i) {
        o[k] = values[i];
        return o;
    }, {});
});
like image 51
Bergi Avatar answered Dec 09 '22 20:12

Bergi