What could be causing the data in my JavaScript array to be replaced when I use myarr.push(mydic)?

Currently, I am working on a function that converts a 3D array into an array of key/value pairs. Below is the code I have written.

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);
  return myarr;
}

My expected output for the new array was:

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

However, I ended up with duplicate entries for "felicia". Instead of the desired output, I got this:

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

I tried adjusting the position of the myarr.push(mydic) method within the loops, but the issue persisted. It seems like something is causing the data to get overwritten, even though I'm using .push().

Here's a screenshot of the output I am getting.

Answer №1

You've been repeatedly adding the same object (mydic) to the array and replacing its content in each loop cycle. Instead, you should aim to generate a fresh object for every iteration of the loop. Take a look at the two lines marked with *** in the code snippet below:

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 ideal for iterating over array elements, check out this answer for a detailed explanation on why and what alternatives you have.

Answer №2

Greetings! Here is a sample code that I created for my most recent project using AngularJs. I have made some modifications so that you can utilize it with plain JavaScript. Hopefully, this will be beneficial for you.

let length = myDictionary.length;
for (let i = 0; i < length; i++){
console.log(i + myDictionary[i]);
myArray.push({
 name: myDictionary[i].name,
 salary: myDictionary[i].salary,
 age: myDictionary[i].age
 })
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can Firebase lists be reversed?

I have searched extensively on SO for an answer to this question, but I haven't found a solution yet. Therefore, please do not mark this as a duplicate. Currently, I am working with AngularFire in Angular 2 and Typescript. I am using FirebaseListObse ...

What is causing a linked list to be altered by changing a variable that is not directly related to it?

I am currently working on implementing a linked list and encountering issues at the basic level. My goal is to add a new node (referred to as wordNode) to the existing linked list, which I have defined as wordList. In my main C file, I have initialized a n ...

What is the best place to define data that remains constant?

In a Vue component, I am looking to utilize data that remains constant. The issue arises when attempting to implement the following code: const numbers = [1, 2, 3] new Vue({ el: "#app" }) <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2 ...

MUI useStyles/createStyles hook dilemma: Inconsistent styling across components, with styles failing to apply to some elements

I have been trying to style my MUI5 react app using the makeStyles and createStyles hooks. The root className is being styled perfectly, but I am facing an issue with styling the logoIcon. Despite multiple attempts to debug the problem, I have not been suc ...

Using jQuery to handle multiple buttons with the same ID

Is there a way to address the issue of multiple buttons sharing the same id? Currently, when clicking on any button, it only updates the record with id=1. How can this problem be resolved? div id="ShowPrace"> <?php try { $stmt = $pdo->prepare(" ...

What is the reason behind classList returning 'undefined' unless getElementById is explicitly used?

Why is it that I can't seem to select multiple elements with the same class (using querySelector, querySelectorAll, getElementsByClassName, etc) and use classList to check if just one div contains a specific class? I've come across tutorials tha ...

Issue encountered: NPM error, unable to find solution for resolving dependency and addressing conflicting peer dependency

I am facing difficulties deploying my project on netlify due to NPM errors. Below are the dependencies: "dependencies": { "@angular/animations": "~15.1.1", ... (list of dependencies continues) ...

Deactivate fields B and C unless input A is provided

http://jsfiddle.net/6Pu3E/ JavaScript Code: $(document).ready(function() { var block = false; if ($('#password').attr('disabled')) { block = false; } else { block = true; } if (block) { $(&a ...

Example of Node-gallery used in isolation, displaying an error event with the message "ENOENT"

I am currently experiencing an issue with the node-gallery npm module. After installing dependencies inside the /example directory, I attempted to run the app. The result was a localhost:3000/gallery page, but upon the page fully loading, I encountered the ...

Highlighting a row upon being clicked

How can I implement a feature in my HTML page that highlights a row when selected by changing the row color to #DFDFDF? If another row is selected, I would like the previously selected row to return to its original color and the newly selected row to be h ...

What is the best way to enforce a required bindings property in an AngularJS component?

Suppose I have the following component defined: angular.module('myApp').component('myComponent', { templateUrl: 'myComponent.html', bindings: { myPropOne: '<', myPropTwo: '<' ...

Validating Input Field with Regular Expression in JavaScript/TypeScript to Avoid Starting with Zero

I need to create a RegEx for a text field in Angular / TypeScript that limits the user to inputting only a 1-3 digit number that does not start with 0. While it's straightforward to restrict input to just digits, I'm struggling to prevent an inpu ...

What is the best way to store multiple arrays within an array in Python?

My goal is to create a 5x5 array in Python that will store a total of 25 arrays. Currently, I am attempting to divide an image into 25 pieces using nested loops in openCV. However, I am struggling with saving the cropped images in the slices array. board = ...

Performing nested GridView calculations in an ASP.NET C# application by utilizing JavaScript/jQuery on the client side

I am facing a challenge with two gridviews inside another gridview where the footers display the total price and tax, while the gross total of all items in the inner gridviews should show in the footer of the main grid (GridView1). ...

Modify the CSS styles (which were set by a preceding function) upon resizing the screen using Javascript

In the mobile version of a website (width less than 620px), there is a button in the header. Clicking this button triggers the "mobileNav" function, which toggles the visibility of the mobile navigation between "display: none;" and "display: flex;". This f ...

Conceal the legend in Highcharts using Python script with Django

Need some assistance with a Django and Highcharts.js project I'm working on. Objective: hide the legend in a Highcharts chart from my views.py script. In my views.py file, I've successfully plotted various charts but struggling to hide the lege ...

How can values be passed to child components in Vue when using component tags for dynamically switching components?

Is there a way to pass values to children components in Vue when using the component tag? It appears that I am unable to pass values to a child component using the component tag without using v-if: <component :is="showNow"></component> ...

Issue with IntelliJ: TypeScript Reference Paths Are Not Relative

I am currently using IntelliJ as my IDE, but I am facing an issue with configuring gulp-typescript to compile my typescript code. The problem arises from the fact that IntelliJ does not treat my reference paths relatively, instead it references them from m ...

Unexpected issue: Ajax success function not displaying anything in the console

My code seems to be running without any output in the console. I am attempting to verify the data in order to trigger specific actions based on whether it is correct or not. However, the if-else conditions are not functioning as expected. Below is a snip ...

Operating on a duplicate of the array is necessary for mapping an array of objects to function properly

I'm starting to uncover a mysterious aspect of Javascript that has eluded me thus far. Recently, I've been pulling an array of objects from a database using Sequelize. This array is quite intricate, with several associations included. Here' ...