Adding elements to an array using push method during a loop where elements are

After experimenting with this code on jsfiddle, I am puzzled as to why it doesn't generate an array of 5 objects, each with a different id property:

var arr = ["1", "2", "3", "4", "5"];
var clone = {"id": "0", "name":"Matthew"};
var arrObj = [];

var idArr = [];

while((a=arr.pop()) != null){ 
    clone.id = a;
    console.log(clone);
    arrObj.push(clone);
}

console.log(arrObj);

What actually appears in the console is:

Object {id: "5", name: "Matthew"} (index):28
Object {id: "4", name: "Matthew"} (index):28
Object {id: "3", name: "Matthew"} (index):28
Object {id: "2", name: "Matthew"} (index):28
Object {id: "1", name: "Matthew"} (index):28

[Object, Object, Object, Object, Object]

Upon inspection, all 5 cloned objects have an "id" value of "1."

The question remains: Why does this happen?

Answer №1

duplicate is considered an entity in programming terms. In the realm of JavaScript, entities are transferred by way of reference, meaning that distinct values are not being transmitted to each position.

Below is a solution that may prove effective:

while((b=arr.shift()) !== undefined){
    var duplicate = {"num": b, "title":"John"};
    duplicate.num = b;
    objArray.push(duplicate);
}

console.log(objArray); 

Outcome:

Array [
    Object {num: "5", title: "John"}
    Object {id: "4", name: "John"}
    Object {id: "3", name: "John"}
    Object {id: "2", name: "John"}
    Object {id: "1", name: "John"}
]

Answer №2

In JavaScript, objects are copied by reference which means you need to create duplicates using methods like jQuery.extend.

var numbers = ["1", "2", "3", "4", "5"];
var person = {"id": "0", "name":"Samantha"};
var objectArray = [];

var idArray = [];

while((n=numbers.pop()) != null){ 
    person = $.extend({}, person);
    person.id = n;
    console.log(person);
    objectArray.push(person);
}

console.log(objectArray);

Answer №3

In the event that your duplicate does not include any functions, you can utilize the following method:

while((a=arr.pop()) != null){
    copy = JSON.parse(JSON.stringify(copy));
    copy.id = a;
    console.log(copy);
    arrObj.push(copy);
}

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

Issue: A child component's function is unable to update the state of the parent component

I have been working on a project using React. Below is the code for the parent component: class Parent extends Component { constructor(props) { super(props); this.state = { deleteConfirm: false }; } onDelete = pass => { thi ...

I am encountering an issue where I am unable to successfully concatenate a string result to a variable within an express router. Instead of receiving the expected

I have been working on looping through an array to retrieve the value and then searching the database. After that, I want to add the database result to the translated string. app.get('/translate',function(req,res) { let translate = '&apos ...

Tips for utilizing both the Element Selector and Class Selector in Jquery

I am working with a simple table that has TDs assigned either the 'PLUS' or 'MINUS' class. My goal is to use jQuery to implement functionality for collapsing all or expanding all. When the Expand All button is clicked, I need to chang ...

Develop an outline using D3.js for the clipath shape

After successfully creating a shape with a color gradient, I encountered the need for further customization. If you are interested in this topic, check out these related questions: Add multi color gradient for different points in d3.js d3.js scatter plot c ...

Issue with retrieving the current location while the map is being dragged

How can I retrieve the current latitude and longitude coordinates when the map is dragged? I've tried using the following code: google.maps.event.addListener(map, 'drag', function(event) { addMarker(event.latLng.lat(), event.la ...

Using multiple instances of the jQuery datepicker within a datalist

I have successfully implemented the jQuery date picker, but I am encountering an issue where it only works on the first textbox within the datalist. I am struggling to extend the functionality of the datepicker to work on all textboxes within the datalist. ...

The correct method for creating an external JSON file

As I browse through numerous JSON tutorials online, including those on STO, I find myself in a state of confusion when it comes to determining the right approach for writing an external JSON file. I have come across various examples such as: (although Ad ...

Why is my data not being sent with the $http POST request in AngularJS?

using angularjs to fetch data with $http userId = '1'; $http({ url: "php/loadTab.php", method: "POST", data: userId }).success(function(data, status, headers, config) { console.log(data); }).error(function(data, status, headers, config) { } ...

Resolving the problem of degrading image quality in HTML Canvas

Recently, I came across an issue while trying to display graphics on an HTML page using canvas. The problem I encountered was that the canvas element was somehow reducing the quality of my images during rendering, especially after some time. Let me visual ...

How can you identify changes in localstorage and then trigger the activation of a new boot file or reallocate a value using Vue.js or JavaScript?

When users log in, they have the option to choose from 3 domains: dev, demo, and sandbox. The configuration for these domains is set in the Boot.js file using Axios. The boot file is triggered prior to the firing of the Vue instance. Below is the content o ...

Error in finding the element with Selenium webdriver 2.0 was encountered

I can't seem to find the element with the specified class name. Here's a snippet of the HTML code: <a class="j-js-stream-options j-homenav-options jive-icon-med jive-icon-gear" title="Stream options" href="#"></a> I attempted to gen ...

Guide to Performing Integration Tests on (AngularJS) Web Applications

I'm currently in the process of developing a Webapp that consists of two main parts: a node rest server and an angularjs client. The structure of the app is as follows: Rest Server <--> Api Module <--> Angular App At the moment, the serv ...

In what way can a container impact the appearance of a child placed in the default slots?

Visiting the vue playground. The main goal is for the container component to have control over an unspecified number of child components in the default slot. In order to achieve this, it's assumed that each child component must either hold a propert ...

Navigating between routes with React-router v4: A beginner's guide

There seems to be an issue with the routing functionality in my project. Currently, only the first component, Cloud, is being rendered on the / route. However, when I try to add other routes, they don't seem to work as expected. import React from &a ...

AngularJS iu.mask is a powerful tool for validating user input, especially when

Currently, I am learning Angular and have created an input field with type 'text' to display a date in the format "99/99/9999" using ui.mask. I have also implemented validation in the module to prevent submission (unblocking button) if the entere ...

Dependency injection in Angular 2 pipes

Greetings everyone! I'm a newcomer to angular 2 and currently trying my hand at creating a custom pipe/filter. However, I've encountered an issue when attempting to inject the pipe I created inside app.ts as shown in the image linked here. Here ...

Implementing Material UI datetime-local feature with no minute selection

Is there a way to hide minutes in a TextField with type = datetime-local? <TextField label="From" type="datetime-local" InputLabelProps={{ shrink: true, }} /> This is how it appears on my end: screenshot ...

problem accessing array values outside of function in JavaScript?

I am facing an issue with my code. I have created an array to store dynamic values from a database. The problem is that when I try to print the array outside of the transaction function, it doesn't display any values even though I have declared the ar ...

Attempting to call setState (or forceUpdate) on a component that has been unmounted is not permissible in React

Hello everyone! I am facing an error message in my application after unmounting the component: Warning: Can't call setState (or forceUpdate) on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, canc ...

The persistent issue with JavaScript variables constantly resetting to zero is causing frustration

Currently, I am developing a small tile matching game where the variable "bestTime" saves the time taken to complete each session. The value of "bestTime" is then displayed as text using the variable "bestTimeTxt." Once a session is completed, a link will ...