javascript: convert two dimensional array to array of objects using the first 'row' to define properties
Solution 1:
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;
}, {});
});
Solution 2:
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/
Solution 3:
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;
});
Solution 4:
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)
Solution 5:
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