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
Hey by using the library underscore.js (http://underscorejs.org/#object) you can accomplish this really easily like this:
var array = [['country', 'population'],['someplace', 100],['otherplace', 200]];
var output = [];
for(var index=1; index<array.length; index++){
output.push(_.object(array[0],array[index]));
}
console.log(output);
Checking this link: http://jsfiddle.net/BqA3Y/2/
You would need to use a bit of iteration to do this! The following code is an untested example to demonstrate what you would have to do.
function convertToObjectArray(table)
{
var output = [];
for(var i = 1; i < table.length; i++)
{
var obj = {};
for(var x = 0; x < table[0].length; x++)
obj[table[0][x]] = table[i][x];
output.push(obj);
}
return output;
}
Another note with this example is you should edit this, however, to make sure the subsequent arrays are the same length or you could run into null values.
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;
}, {});
});
var array = [
['country', 'population'],
['someplace', 100],
['otherplace', 200]
];
var objects = [], one = array[0][0], two = array[0][1];
for (var i = 1, len = array.length; i < len; i++) {
var object = {};
object[one] = array[i][0];
object[two] = array[i][1];
objects.push(object);
}
console.log(objects);
DEMO
let array = [['country', 'population'],['someplace', 100],['otherplace', 200]];
let [keys, ...rows] = array;
let result = rows.map(r => (keys.reduce((o, k, i) => (o[k] = r[i], o), {})));
console.log(result)
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;
});