mardi 2 juillet 2019

JavaScript: Create Function that Transforms Data in Nested Arrays to One Array with Multiple Objects

I want to create a function called transformEmployeeData that transforms some employee data from one format to another.

argument:

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

My desired output is:

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

Below is the code I tried:

function transformEmployeeData(employeeData) {
  // your code here

  //console.log(employeeData)

  let result = []; 

  let obj = {}; 

  //console.log(employeeData.length)

  for (let i=0; i<employeeData.length; i++){
    let element = employeeData[i];

    //console.log(element) 


    for (let k=0; k<element.length; k++){
      let indElem = element[k]

      console.log(indElem)
      //console.log(element[0])

      obj[indElem[0]] = indElem[1]; 

    }
    result.push(obj); 
  }
  return result; 
}


transformEmployeeData(input)

The code above produces the incorrect output below:

[ { firstName: 'Mary',
    lastName: 'Jenkins',
    age: 36,
    role: 'manager' },
  { firstName: 'Mary',
    lastName: 'Jenkins',
    age: 36,
    role: 'manager' } ]

What am I doing wrong? I appreciate if a conceptual explanation along with correct code can be provided.

Aucun commentaire:

Enregistrer un commentaire