Home > Net >  Moving variables in nested Loop JavaScript
Moving variables in nested Loop JavaScript

Time:05-26

function transformEmployeeData(employeeData) {
  var arr = [];
  var obj = {};
  for (var i = 0; i < employeeData.length; i  ) {

    var personArr = employeeData[i];
    for (var j = 0; j < personArr.length; j  ) {
      var key = personArr[j][0];
      var value = personArr[j][1];
      obj[key] = value;
    }
    arr.push(obj);
  }
  return arr;
}

input = [
  [
    ['firstName', 'Joe'],
    ['lastName', 'Blow'],
    ['age', 42],
    ['role', 'clerk']
  ],
  [
    ['firstName', 'Mary'],
    ['lastName', 'Jenkins'],
    ['age', 36],
    ['role', 'manager']
  ]
];

var getData = transformEmployeeData(input);
console.log(getData);

And I want my result to be like this:

[
    {firstName: 'Joe', lastName: 'Blow', age: 42, role: 'clerk'},
    {firstName: 'Mary', lastName: 'Jenkins', age: 36, role: 'manager'}
]

So I moved var obj = {}; into the first for loop, and I got the right result. But I still cannot figure out why I have to move it inside the loop? what is the difference? Please help, thank you!

CodePudding user response:

If you don't put it in the loop, you are defining a single object and are just modifying its contents within the loop body and pushing that single object into the array.

But, if you include it inside the loop, you create a new object each time the loop body executes (and the existing variable stops pointing to the previous object and now references the new one) and then push that new object into the array, resulting in multiple objects in your output.

CodePudding user response:

If you do not add the object in the first loop, you are creating a single object for the whole function execution which can override previous properties of the first loop by the second one

  • Related