I'm working on a little problem in JS (not graded or for school, just for practice), and can't seem to get it quite right.
The aim is to write a function that converts a multi-dimensional array to an array of objects. For example, the input could be:
var data = [
[
['firstName', 'Joe'], ['lastName', 'Blow'], ['age', 42], ['role', 'clerk']
],
[
['firstName', 'Mary'], ['lastName', 'Jenkins'], ['age', 36], ['role', 'manager']
]
]
And this should be the output:
[
{firstName: 'Joe', lastName: 'Blow', age: 42, role: 'clerk'},
{firstName: 'Mary', lastName: 'Jenkins', age: 36, role: 'manager'}
]
Here is what I have so far:
function transformEmployeeData(array) {
var object = {};
var objectsArray = [];
for (i=0; i<array.length; i++) {
for (j=0; j<array[i].length; j++) {
var keys = array[i][j][0];
object[keys] = array[i][j][1];
} objectsArray.push(object);
}
return objectsArray);
}
It's almost right, but I get this as output:
[ { firstName: 'Mary',
lastName: 'Jenkins',
age: 36,
role: 'manager' },
{ firstName: 'Mary',
lastName: 'Jenkins',
age: 36,
role: 'manager' } ]
How do I go about fixing the function so that it doesn't spit out the same thing twice?
Thanks for your help!
mapandreducelike this.