I'm working on an assignment involving converting arrays to objects, and I'm a little tied up. We start with an array, containing two additional nested arrays, each of which contain a variable number of arrays (consisting of two values each).
The assignment is to convert all of this into one array, containing multiple objects. Within each object, there will be a series of key/value pairs equal to the two values from each of the smallest given arrays.
E.G.
The argument will look like this:
[
[['firstName', 'Joe'], ['lastName', 'Blow'], ['age', 42], ['role', 'clerk']],
[['firstName', 'Mary'], ['lastName', 'Jenkins'], ['age', 36], ['role', 'manager']]
]
Given that input, the return value should look like this:
[{firstName: 'Joe', lastName: 'Blow', age: 42, role: 'clerk'}, {firstName: 'Mary', lastName: 'Jenkins', age: 36, role: 'manager'}]
Using debugger, I've determined that my code correctly assigns key/value pairs to the first object in the return statement. However, when the loop continues, instead of creating a new nested object, the key/value pairs from the first object are replaced, so I only end up with one object with the correct key value pairs from the final array that is evaluated.
Here's my code so far:
function transformEmployeeData(employeeData) {
var obj = {}, arr = []
for (var i = 0; i < employeeData.length; i ++) {
for (var j = 0; j < employeeData[i].length; j ++) {
var key = employeeData[i][j][0];
var value = employeeData[i][j][1];
obj[key] = value;
}
arr.push(obj);
}
return arr;
}
This one has my brain a little tied in knots...Any advice would be greatly appreciated!!!