0

JS newbie here. I'm learning to convert a nested array into an array containing objects.

My question: Why does var outObj = {}; turns into an array after pushing outobj{} into outArr[]?
(Please see expected and actual output at the end of this post) Thank you in advance for your help.

function transformEmployeeData(inArr) {
  var outArr = []; 

  for(var x = 0; x < inArr.length; x++){

    var outObj = {}; // The obj that will be stores in outArr[]
    var a1 = inArr[x]; 
    //console.log(a1 + '\n');

    for(var y = 0; y < a1.length; y++){
      outObj[a1[y][0]] = a1[y][1];
      //console.log(outObj[a1[y][0]]);
    }
    outArr.push(outObj);
  }
  return arr;
}

var arr = [
    [
        ['firstName', 'Joe'], ['lastName', 'Blow'], ['age', 42], ['role', 'clerk']
    ],
    [
        ['firstName', 'Mary'], ['lastName', 'Jenkins'], ['age', 36], ['role', 'manager']
    ]
];
console.log(transformEmployeeData(arr)); 
/* 
Expected Output:
[
    {firstName: 'Joe', lastName: 'Blow', age: 42, role: 'clerk'},
    {firstName: 'Mary', lastName: 'Jenkins', age: 36, role: 'manager'}
]

Actual Output:
[ [ [ 'firstName', 'Joe' ],
    [ 'lastName', 'Blow' ],
    [ 'age', 42 ],
    [ 'role', 'clerk' ] ],
  [ [ 'firstName', 'Mary' ],
    [ 'lastName', 'Jenkins' ],
    [ 'age', 36 ],
    [ 'role', 'manager' ] ] ]
*/
1
  • You are returning the value you are passing to the function (indirectly). Do console.log(transformEmployeeData([])); and be surprised ;) Commented Oct 21, 2017 at 4:08

1 Answer 1

1

Return outArr instead of arr from transformEmployeeData() function call

return outArr;
Sign up to request clarification or add additional context in comments.

1 Comment

Phew....thanks so much @guest271314 Learning everything and sorting out everything at once made my mind tired.

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.