1

I am attempting to change an array of arrays containing two value arrays into an array of two objects.

I'm fairly new to JS and I'm not sure where my code is wrong. The array being logged to the console contains the same two objects.

let myArray = [
  [
    ['name', 'John'],
    ['job', 'Janitor']
  ],
  [
    ['name', 'Rob'],
    ['job', 'CEO']
  ]
];

function transformEmployeeData(array) {
  let arrayOfObjects = [];
  let newObj = {};
  // iterates through employees
  for (let i = 0; i < array.length; i++) {
    // resets obj to empty
    newObj = {};
    // iterates through employees properties
    for (let j = 0; j < array[i].length; j++) {
      newObj[array[j][j][0]] = array[j][j][1];
    }
    // pushes object into array
    arrayOfObjects.push(newObj);
  }
  return arrayOfObjects;
}

console.log(transformEmployeeData(myArray));
Obsidian Age
  • 36,816
  • 9
  • 39
  • 58
  • 4
    `newObj[array[j][j][0]] = array[j][j][1];` should be `newObj[array[i][j][0]] = array[i][j][1];`. Voting to close as a *typo* – Phil Dec 08 '17 at 02:49
  • Thanks! The only problem still is that the key pairs in each object are displaying in the wrong order. Job is before Name. Why is this? – Zach Coursey Dec 08 '17 at 02:52
  • 4
    Object key order [cannot be guaranteed](https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order) and does not make any difference anyway – Phil Dec 08 '17 at 02:52

3 Answers3

0

This should work. Nested forEach loops then create the object a the end.

let myArray = [
  [
    ['name', 'John'],
    ['job', 'Janitor']
  ],
  [
    ['name', 'Rob'],
    ['job', 'CEO']
  ]
];

function arrayToObj(arr){
    var myObj ={};
    arr.forEach(function(val){
        val.forEach(function(val2){
            myObj[val2[0]] = val2[1];
            console.log(myObj);
        });
    });
}
andre mcgruder
  • 1,058
  • 1
  • 9
  • 11
0

when faced with an nexted array problem, it is not recommended to use arr[i][j][k]...

you can do this:

        function transformEmployeeData (array) {
            if (!Array.isArray(array) || array.length === 0) {
                return []
            }

            return array.map(item => {
                const obj = {}
                if (Array.isArray(item)) {
                    item.reduce((a, b) => {
                        if (a) {
                            obj[a[0]] = a[1]
                        }
                        obj[b[0]] = b[1]
                    })
                }
                return obj
            })
        }
daiqingyun
  • 21
  • 1
-1

Your code is wrong here:

newObj[array[j][j][0]] = array[j][j][1];

Should be:

newObj[array[i][j][0]] = array[i][j][1];
Daniel Tran
  • 5,531
  • 9
  • 22