The task is the following:
Write a function called "transformEmployeeData" that transforms some employee data from one format to another.
The argument will look something 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'}
]
Note that the input may have a different number of rows or different keys than the given sample.
For example, let's say the HR department adds a "tshirtSize" field to each employee record. Your code should flexibly accommodate that.
I tried this:
function transformEmployeeData(array) {
var obj = {}, arr = [];
array.forEach(function(cv){
for(var i = 0, l = cv.length; i < l; i++) {
obj[cv[i][0]] = cv[i][1];
}
arr.push(obj);
});
return arr
}
I got back two objects but they're both {firstName: 'Mary', lastName: 'Jenkins', age: 36, role: 'manager'}
I thought doing this in the body of the loop would solve the problem because I thought (wrongly) it was a scope issue.
(function(i){
obj[cv[i][0]] = cv[i][1];
}(i));
Any help will be appreciated as always!
forloop could have beencv.forEach. There's no need to write explicit loops like that anymore for arrays.