Using the "push" method to create an array of objects in Javascript

I am relatively new to Javascript and I've encountered an issue in my code that I can't quite figure out.

My objective is to build an array of "people" where each person has specific information such as an "id" and a "name". Since I don't know the exact number of "people" ahead of time, I'm using the "push" method whenever I need to add another individual. The problem arises when all the entries in my array end up reflecting the data of the latest person added.

Below are the declarations I'm working with:

var ppl_arr = [];
var profile = {
  id: 10000,
  name: "",
};

profile.id = 3;

ppl_arr.push(profile);
alert(ppl_arr[0].id + "\t" + ppl_arr.length);

profile.id = 5;
ppl_arr.push(profile);
alert(ppl_arr[0].id + "\t" + ppl_arr[1].id + "\t" + ppl_arr.length);

The first alert functions correctly: "3 1"
However, the second alert outputs: "5 5 2" instead of the expected "3 5 2"

Essentially, I'm successfully adding two individuals to my array, but it seems like the data for the second person overrides the first one. Can anyone shed some light on what's happening here?

Answer №1

Instead of simply changing the id of the existing object and adding it to the array multiple times, a better approach would be to create instances of 'people' objects using a constructor function like the one shown below:

// Constructor function for creating Person objects
function Person(id, name) {
    this.Id = id;
    this.Name = name;
}

Then you can populate an array with these Person objects as follows:

var peopleArr = [];

peopleArr.push(new Person(3, "Bob")); // Add Bob to the array

alert(peopleArr[0].Id + " - " +  peopleArr.length); // Outputs "3 - 1"

peopleArr.push(new Person(5, "Steve")); // Add Steve to the array

alert(peopleArr[0].Id + "\t" + peopleArr[1].Id + "\t" + peopleArr.length); // Outputs "3  5  2"

Answer №2

Question #1:

alert(ppl_arr[0].id + ppl_arr.length);
will show the total, not the combination - test
alert(ppl_arr[0].id.toString().concat(ppl_arr.length));

Question #2:

Modifying the id attribute of an existing object changes it directly, rather than making a copy. Therefore, any changes to the id affect the object stored in the array as well. To resolve this, you would need to:

var ppl_arr = [];
var profile = {
  id: 10000,
  name: " ",
};

profile.id=3;
ppl_arr.push(profile);

//Create a new profile
var profile2 = { 
  id: 10000,
  name: " ",
};

profile2.id=5;
ppl_arr.push(profile2);

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

Top guidelines for formatting an npm module

As I develop an npm module, my goal is to take data from a JavaScript array of objects and provide users with the ability to filter out only the relevant information. In the early stages of designing the module's API, I am considering which approach ...

Retrieve a value from a list in robot automation framework

I am trying to retrieve the values from a list that I have declared called @{EMAIL_LIST with 3 values in it) My code snippet looks like this: : FOR ${a} IN RANGE 0 3 \ Input Text id=username @{EMAIL_LIST}[a] However, I am encou ...

Is there a way I can utilize canvas to overlay one image onto another?

Is there a way to merge one image into another by using a transparent box? It's not just about copying and pasting an image into another. I also want to know how to transform the image to fit perfectly within the other image. For example, similar to ...

Steps on removing a file type from a Material UI textfield

I've been struggling to figure out how to clear a Material UI textfield with type="file" even after trying multiple approaches. My issue arises when I set a file size limit and display an error message if a user tries to upload a file larg ...

What is the correct way to define a function parameter when using AngularJS Emit?

I've been exploring the emit feature in AngularJS and had a question about passing a function as an argument. In the Parent Controller: $scope.$on("getChildFunction", function(event, func) { console.log("The function is...", func); }) In the Ch ...

designing a visually appealing pre-loader page that appears before the content loads

I am attempting to recreate the loading animation from this page. When the page loads, an SVG and background image appear, but once the user starts scrolling, the page quickly moves to the actual content and the loader is no longer visible or accessible ...

How can you determine if a mouseover event is triggered by a touch on a touchscreen device?

Touchscreen touches on modern browsers trigger mouseover events, sometimes causing unwanted behavior when touch and mouse actions are meant to be separate. Is there a way to differentiate between a "real" mouseover event from a moving cursor and one trigg ...

What is the best way to continuously call an asynchronous method in native JavaScript until a successful response is received?

There is a scenario where I have an asynchronous method that can either return success or failure. The requirement is to repeatedly call this async method from another function until it returns success. However, if it fails consecutively for 5 times, the ...

Autocomplete's `getOptionLabel` function unexpectedly returned an object ([object Object]) instead of the expected string

Currently delving into the world of ReactJS and working with @mui controls, specifically a Multiselect Dropdown with autocomplete feature. Here is the child component causing me some trouble, displaying the following error message: "index.js:1 Materi ...

Learn the step-by-step process of graphing equations in React similar to Desmos

I am currently attempting to create a graph of an equation based on user input, similar to how it is done on Desmos () For example While I have come across a function plotting tool at , I have encountered difficulties when trying to plot equations contai ...

Is it necessary to make a distinct route for SocketIO implementation?

I am new to Socket.IO and I recently completed the chat tutorial in the documentation along with some additional tasks to gain a better understanding of how it works. Currently, I am attempting to establish a connection between a NodeJS server and a React ...

Overusing For Loops for Cloning in JavaScript

REVISED: (I have pinpointed the issue previously discussed in the comments) this is the code I am working with: <script type="text/javascript"> for(var i=0; i<5; i++){ $(".image-wrap").clone().appendTo(".container").attr(&apo ...

Encountering a bizarre npm issue while attempting to execute npm install for brain.js

Encountering a puzzling error while attempting to install brain.js. Unsure of why Python is being mentioned during the installation process via npm, as there are no similar situations found on Google (and I'm not quite sure how to search for it). G:& ...

Is there a method to condense it further, possibly utilizing recursion? Java

Is there a way to optimize this code and make it shorter? I think recursion might be the solution, but it's not my strong suit. Also, something needs to happen at each computed state which seems daunting. public void VertexState() { // Try to find t ...

Tips for re-entering data retrieved from mysql into another database table

I have retrieved these grocery product values from the database. Customers can input their desired quantity in the respective textboxes. Now, I need to update these values in the database table along with the quantity information. How can I achieve this? W ...

When I attempt to use document.execCommand("copy"), the line break does not get applied

I am currently using the following code to create a string and copy it. However, when I paste it as output, the line break is not being applied. function copyToClipboardShipto() { var $temp = $("<input>"); $("body").append($ ...

Is there a way to automatically retrieve CSV data using ashx on a web page?

After researching the provided links from SO without success, I decided to reach out here for help. (For privacy reasons, the actual URL and header data have been obscured) I am struggling to automate downloading data from an HTTPS web page using Delphi ...

Using webpack without integrating babel can lead to compatibility issues with certain JavaScript

Struggling to create a basic demonstration using webpack and babel, I can't seem to pinpoint the issue. With webpack version 1.13.3 installed, attempting to add npm install --save-dev babel-core babel-preset-es2015 or npm install --save-dev babel-load ...

Integrate Jade mixins programmatically into an Express application using JavaScript

Within my Express application, I have a file that contains many beneficial Jade mixins. My objective is to utilize this file across various projects by creating an NPM module (hosted in our company's private registry) that will incorporate these mixin ...

What is the best way to make a CSS class appear in my javascript using the method I have been using before?

I am facing an issue in making this code work properly. It functions correctly for my caption element as there is only one caption tag in my HTML. However, the same code does not work for my TR element since it requires a for loop to iterate through multip ...