2

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!

3
  • 1
    Your inner for loop could have been cv.forEach. There's no need to write explicit loops like that anymore for arrays. Commented Apr 20, 2017 at 23:52
  • @4castle Is it because of speed? It did dawn on me but sometimes I can't help why my brain pan defers to different patterns... Commented Apr 20, 2017 at 23:55
  • It's not so much about speed, but about having more declarative code. Say what and not how. Commented Apr 21, 2017 at 0:01

2 Answers 2

2

You are correct it is a scope issue. You should define a new obj in each iteration of the forEach, not outside it.

function transformEmployeeData(array) {
    var arr = [];
    array.forEach(function(cv){
        var obj = {};
        for(var i = 0, l = cv.length; i < l; i++) {
            obj[cv[i][0]] = cv[i][1]; 
        }
        arr.push(obj);
    });

  return arr
}
Sign up to request clarification or add additional context in comments.

Comments

2

function transform(arr) {                    
  return arr.map(function(sub) {             // for each subarray sub of the array arr
    return sub.reduce(function (obj, a) {    // create a new object obj
      obj[a[0]] = a[1];                      // set the key in a[0] to the value a[1]
      return obj;
    }, {});
  });
}

var array = [[["firstName","Joe"],["lastName","Blow"],["age",42],["role","clerk"]],[["firstName","Mary"],["lastName","Jenkins"],["age",36],["role","manager"]]];

console.log(transform(array));

Or even shorter in recent ECMAScript versions:

function transform(arr) {                    
  return arr.map(sub => sub.reduce((obj, a) => (obj[a[0]] = a[1], obj), {}));
}

var array = [[["firstName","Joe"],["lastName","Blow"],["age",42],["role","clerk"]],[["firstName","Mary"],["lastName","Jenkins"],["age",36],["role","manager"]]];

console.log(transform(array));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.