user211309 user211309 - 2 months ago 13
Javascript Question

Array to object in Javascript

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!

Answer

Your code creates a single instance of an object, then overwrites the values in that instance.

To fix, create a new object every time:

function transformEmployeeData(array) {
    var objectsArray = [];
    for (i=0; i<array.length; i++) {
       var object = {};
       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);
}