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;
}
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;
}, {});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With