The problmem you face can be solved using for loops, as you were trying, if you use your indexes correctly.
If you format your data as I did, you will see that there is three levels for your indexes your [i,x,y];
for example for employeeData[0] you should get:
[
['firstName', 'Bob'],
['lastName', 'Lob'],
['age', 22],
['role', 'salesperson']
]
then for employeeData[0][0] you should get:
['firstName', 'Bob']
and for employeeData[0][0][0] you should get: 'firstName'
To access 'Bob' you would need to employeeData[0][0][1] and since you know that there is only two elements in this inner array you don´t need to loop though it.
as @TallChuck suggested great part of your problem stems from forgetting to use your x index.
var employeeData = [
[
['firstName', 'Bob'],
['lastName', 'Lob'],
['age', 22],
['role', 'salesperson']
],
[
['firstName', 'Mary'],
['lastName', 'Joe'],
['age', 32],
['role', 'director']
]
]
function transformData(employeeData) {
let newObject = {};
let newArr = [];
for (var i = 0; i < employeeData.length; i++) {
for (var x = 0; x < employeeData[i].length; x++) {
newObject[employeeData[i][x][0]] = employeeData[i][x][1];
}
newArr.push(newObject);
newObject = {};
}
return newArr;
}
console.log(transformData(employeeData));
EDIT
You could also make some more complex solutions if you pay attention to your indexes. Say you have the following data:
var employeeData = [
[
['firstName', 'Bob', 'weight', '80kg'],
['lastName', 'Lob'],
['age', 22],
['role', 'salesperson']
],
[
['firstName', 'Mary', 'eye color', 'green'],
['lastName', 'Joe'],
['age', 32],
['role', 'director']
]
]
Then the solution I gave before wouldn´t work directly. But if you look closely you will see that in some of the arrays your field names are located in the positions 0, 2 of the Y index. Which means that your field names are in a pair positions and the filed values in the odd positions. So you can actually make a loop through y and just check if the Y index is divisible by 2.
if(y % 2 == 0 ..){}
And do this only if there is an accompanying odd value thus
if(y % 2 == 0 && employeeData[i][x][y+1]){..}
The full code is below.
var employeeData = [
[
['firstName', 'Bob', 'weight', '80kg'],
['lastName', 'Lob'],
['age', 22],
['role', 'salesperson']
],
[
['firstName', 'Mary', 'eye color', 'green'],
['lastName', 'Joe'],
['age', 32],
['role', 'director']
]
]
function transformData(employeeData) {
let newObject = {};
let newArr = [];
for (var i = 0; i < employeeData.length; i++) {
for (var x = 0; x < employeeData[i].length; x++) {
for (var y = 0; y < employeeData[i][x].length; y++) {
if(y % 2 == 0 && employeeData[i][x][y+1]){
newObject[employeeData[i][x][y]] = employeeData[i][x][y+1];
}
}
}
newArr.push(newObject);
newObject = {};
}
return newArr;
}
console.log(transformData(employeeData));