0

Currently writing a function that takes a 3D array and makes the values into an array of key/value pairs. Below is my code.

function arrToDictArray(array) {
  var myarr = [];
  var mydic = {};
  var x = 0;
  for (var i in array) {
    console.log("i: " + i);
    var x = array[i];
    for (var j in x) {
      console.log("j: " + j);
      mydic[array[i][j][0]] = array[i][j][1];
      console.log(mydic[array[i][j][0]]);
    }
    myarr.push(mydic);
    //console.log(myarr);
    //console.log(myarr[i]);
  }
  console.log(myarr);
  return myarr;
}

I was expecting for my new array to show

[{name:'Mauri', salary: 100000, age:40},{name: 'felicia', salary: 120000, age:36}] 

but instead I get felicia duplicated.

[{name: 'felicia', salary: 120000, age:36},{name: 'felicia', salary: 120000, age:36}] 

I tried to change my myarr.push(mydic) method in the j loop and outside of the i and j loop entirely but it still gets overwritten. I can't seem to see why a .push() is overwriting anything.

Screenshot of my output.

Community
  • 1
  • 1
Diana Lee
  • 41
  • 2
  • 8
  • 1
    It would help us help you better if you showed us what the array you pass *into* the function is. *(I've taken a guess based on what the function does, but it's a guess...)* – T.J. Crowder Aug 25 '17 at 07:46

2 Answers2

0

You're pushing the same object (mydic) onto the array multiple times, and overwriting what's inside that one object on each loop iteration. Instead, you want to create a new object for each loop iteration. See the two *** lines in the snippet:

function arrToDictArray(array) {

    var myarr = [];
    var mydic;                           // ***
    var x = 0;

    for (var i in array) {
        mydic = {};                      // ***
        //console.log("i: " + i);
        var x = array[i];
        for (var j in x) {
            //console.log("j: " + j);
            mydic[array[i][j][0]] = array[i][j][1];
            //console.log(mydic[array[i][j][0]]);
        }
        myarr.push(mydic);
    }
    console.log(myarr);

    return myarr;
}

arrToDictArray([
    [
        ["name", "Mauri"],
        ["salary", 100000],
        ["age", 40]
    ],
    [
        ["name", "felicia"],
        ["salary", 120000],
        ["age", 36]
    ]
]
);
.as-console-wrapper {
  max-height: 100% !important;
}

Side note:

  • for-in isn't meant for looping through array entries, see this answer for a full explanation of why not and what your various options are.
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
-1

hi its an example code i have written in for my latest angularJs project and i modified it to so you can use it in plain javascript hope it will work for you

var len = mydic.length;
for (var i = 0;i < len ; i++){
console.log(i + mydic[i]);
myarr.push({
 name: mydic[i].name,
 salary: mydic[i].salary,
 age: mydic[i].age
 })
}
Emad Fani
  • 415
  • 4
  • 13