Odd replication occurring while storing object attributes in an array

JSFiddle

I am trying to iterate through an object, make changes to each property, and then add them to an array. Each property is added multiple times (in the JSFiddle example, I have set it to be added twice for simplicity). Each iteration should have some unique properties modified (the JSFiddle only shows modification of the 'number' property).

However, I am facing an issue where all the objects pushed in a single loop end up with identical properties. I am looking for a solution to address this problem.

Apologies for any language barriers, explaining the issue can be challenging and it would be easier to understand by looking at the JSFiddle.

Current output:

[{ x: 1, number: 1 },  
{ x: 1, number: 1 },  
{ y: 2, number: 1 },  
{ y: 2, number: 1 },  
{ z: 3, number: 1 },  
{ z: 3, number: 1 }] 

Desired output:

[{ x: 1, number: 0 },
{ x: 1, number: 1 },
{ y: 2, number: 0 },
{ y: 2, number: 1 },
{ z: 3, number: 0 },
{ z: 3, number: 1 }]

Code:

var items = { 
  "a": {
    "x": 1
  },
  "b": {
    "y": 2
  },
  "c": {
    "z" : 3
  }
};

var something = [];

for ( var key in items ) {
  var item = items[key];
  if ( items.hasOwnProperty(key) ) {
    for ( var i = 0; i < 2; i++ ) {
      item.number = i;
      something.push(item);
    }
  }
}

console.log(something);

Answer №1

Let's break it down with a dry run example. In the loop below, we start by selecting the first key "a" from your 'items' object. Now, let's delve into the loop:

    for ( var key in items ) {

      // Key is now set to "a"
      
     var item = items[key]; 

     // The variable 'item' now points to the object items["a"], which is {"x":1}

      if ( items.hasOwnProperty(key) ) {
        for ( var i = 0; i < 2; i++ ) {

          // During the 1st iteration, 'item' refers to {"x":1}
          // During the 2nd iteration, 'item' refers to {"x":1,"number":0} (updated in the previous iteration)

          item.number = i;

         // In the 1st iteration, 'item' receives the "number" property, resulting in {"x":1,"number":0} in memory
         // In the 2nd iteration, it continues to modify the same object, leading to {"x":1,"number":1}


          something.push(item);
          // In the 1st iteration, a reference to the object is added to 'something'
          // In the 2nd iteration, another reference to the object is added to 'something' 
          // Both references essentially point to the same object.

        }
      }
    }

If you want the desired output, you should create a copy of your object instead of multiple references. Cloning objects in JavaScript can be tricky. Check out this link for more information: How do I correctly clone a JavaScript object?

A simple solution for your current code would be to implement a clone function that handles deep-cloning issues and prototype-inherited properties. Here's the updated code snippet:

function clone(obj) {
    if (null == obj || "object" != typeof obj) return obj;
    var copy = obj.constructor();
    for (var attr in obj) {
        if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
    }
    return copy;
}
var items = {
  "a": {
    "x": 1
  },
  "b": {
    "y": 2
  },
  "c": {
    "z" : 3
  }
};



var something = [];

for ( var key in items ) {
  var item = items[key];

  if ( items.hasOwnProperty(key) ) {
    for ( var i = 0; i < 2; i++ ) {
      var tempItem = clone(item);
      tempItem.number = i;
      something.push(tempItem);
    }
  }
}

console.log(something);

If you found this helpful, feel free to upvote.

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

FireFox is unresponsive to OPTIONS requests

I have a webpage that is accessed through HTTP. The client-side code is making AJAX requests for authorization to the same domain, but using HTTPS, which causes CORS issues. When using FireFox, the request looks like this: // domains and cookies are chang ...

Dependable timekeeping tool for an online discussion platform

Seeking assistance in selecting the best solution (nodeJS + socket.io + redis) for a chat room timer. In this scenario, multiple Rooms are created with each room having a designated HOST or admin and up to 500 members. The number of rooms can vary at any ...

Creating a compact array from a larger array in JavaScript

I am currently using the jquery.bracket library and I am looking to split a large array into pairs like ["'Team 1', 'Team 2'"],["'Team 3', 'Team 4'"] from var all= ["'Team 1', 'Team 2'","'T ...

What could be causing my bootstrap-switch to malfunction?

Here is the snippet of code I am working with: jQuery.each($('.onoffswitch-checkbox'), function(i, slotData) { console.log($(slotData).bootstrapSwitch('state')) }) <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1 ...

Deleting items from an array while iterating in Swift 5.1 without needing to reverse

I'm facing a challenge where I need to remove an element within a for-in loop if it doesn't meet a certain condition. While I found a solution here, it seems outdated and overly complex for what I want to achieve. When working with Java, I can e ...

Creating a mask overlay that covers the entire screen while excluding a specific sibling div

My goal is to create a div that acts as a mask covering the entire window. It should have an opacity of 0.5 and a background color of lightgray. However, there is one particular div on the screen that I do not want to be affected by the mask. I attempted t ...

Transforming a static material table into a dynamic one

I need help simplifying my legacy Angular code that involves working with for loops. It's become challenging to follow the existing pattern: <table mat-table [dataSource]="dataSource" matSort> <ng-container *ngFor="let colu ...

Validator returns undefined when expressing invalid data

Having an issue with validation, here is the code snippet: routes.js var express = require('express'); var router = express.Router(); var hello_controller = require('../api/controllers/helloController'); var { validationRules, validat ...

Attempting to swap out the text of a menu item with an icon when it is selected

Here is my very first question on this platform. I have 5 menu items and each has an associated icon. The code snippet for one of the menu items looks like this: <li class="nav-item"> <a class="nav-link currentactive" href=" index.html#getdemo"& ...

Setting up TypeScript in an Angular 2 project and integrating Facebook login

Currently, I am in the process of familiarizing myself with Angular 2 and typescript. Although things have been going smoothly so far, I have hit a roadblock while attempting to implement a Facebook login message. In my search for a solution, I stumbled up ...

Tips for swapping out textures imported from Collada with ShaderMaterial textures in Three.js

Is it possible to update the textures of a basic 3D model loaded using the Collada loader in the Three.js library? My goal is to incorporate color, specular, and normal maps onto the model using ShaderMaterial by referencing new files with the model' ...

Tips for testing React Final Form's Field Components on a unit level

While developing a form component using the react-final-form library, I encountered a situation where the component started growing in size. To address this, I decided to split it into multiple sub-components - with the parent component containing the < ...

How can you conceal an object based on specific conditions in JavaScript?

In my JavaScript code, I am working with an object that stores multiple values. However, I want to be able to hide a specific object under certain conditions. Here is the data structure: $scope.sort={ National : { prop: "Country", classes: { md: ...

Obtain Data Grid from Website

I need to extract a table with the following columns: "Date|Open|High|Low|Close|No.of Shares|No.of trades|Total Turnover|Deliverable Qty" from the website "" Below is the code I am using: Sub Macro_BSE() Application.ScreenUpdating = False Dim File ...

How to extract a column as an array from an Excel file using Python

For a project I'm working on, I need to create a league table and sort it by points. To achieve this, I'm trying to extract the points column from an Excel file and order it. Here's the code I've come up with so far: output = [] x = op ...

Bootstrap 4 - DropDown option - Element is positioned above the navigation bar

Currently facing an issue with the DropDown menu. Whenever I add padding to the DropDown menu (class - drop_link), it ends up pushing the entire element over the <nav>. I'm unsure of how to prevent this from occurring. I attempted to disable som ...

Utilize JavaScript to transform an array into an object using destructuring

Is there a more efficient method to convert a deconstructed array into an object in JavaScript? My current approach involves using the axios API library, and when I make multiple queries simultaneously, I receive an array with 4-5 API responses. I then ne ...

Updating the TextField in React Material UI based on the Slider value without affecting the Slider

Is there a way to update the value of a TextField based on the slider, while still allowing manual input in the TextField? I want the TextField to reflect changes from the slider but not vice versa. I attempted making the TextField a controlled component ...

What is the best way to ensure a jQuery UI slider recognizes when the mouse is released after being clicked?

I have integrated the jQuery slider into my application and am facing an issue with triggering an event to update the database upon releasing the slider. Currently, I am using the following code snippet: $('.ui-slider-handle').mouseup(function () ...

What steps should I take to ensure that model updates are applied by NgJsTree?

One of the challenges I encountered in my project involved integrating various technologies such as JQuery, JSTree, Angular, and NgJsTree. Despite updating the treeData model, the changes were not being reflected in the tree structure. tcwsApp.servi ...