Collection of items consists of identical objects repeated multiple times

Multiple objects are being created and then pushed into the array objArr:

var objArr = [];
var obj = {};
var height = [9,8,7,3,6,5,2,4];

for (var i = 0; i < 8; i++) {
debugger;
  var mountainH = height[i];

  obj.h = mountainH;
  obj.index = i;

  objArr.push(obj);
}

for (var i = 0; i < objArr.length; i++) {

  alert(objArr[i].h);
}

However, it seems that all the objects in the array have the same values. Why might that be?

https://i.sstatic.net/rgnxW.jpg

Answer №1

  • Ensure obj is initialized within the scope of your for-loop.

Avoid overwriting values of a global variable obj.

var objArr = [];

var height = [4,6,8,1,3,7,9,5];

for (var i = 0; i < 8; i++) {
debugger;
  var obj = {};
  var value = height[i];

  obj.height = value;
  obj.position = i;

  objArr.push(obj);
}

for (var i = 0; i < objArr.length; i++) {

  console.log(objArr[i].height);
}

Answer №2

It is important to keep the scope of obj within the for loop in your code, as having it declared globally can lead to overwriting its value on each iteration instead of allocating new memory.

To avoid this issue, declare obj inside the loop like the following example:

var objArr = [];
var height = [9, 8, 7, 3, 6, 5, 2, 4];

for (var i = 0; i < 8; i++) {
  debugger;
  var mountainH = height[i];
  var obj = {};

  obj.h = mountainH;
  obj.index = i;

  objArr.push(obj);
}
console.log(obj);

Answer №3

In order to prevent all array members from sharing the same object reference, make sure to initialize a new object in each loop iteration.

You can simplify your code further by using the .map() method to build the array and fully leveraging the object literal initializer to declare properties.

var height = [9,8,7,3,6,5,2,4];
var objArr = height.map((n, i) => ({h: n, index: i}));

console.log(objArr);

This approach is both more concise and easier to understand. It creates a new object for each number in height and adds it to a fresh array returned by .map().


For an even shorter implementation, take advantage of the newer features available for object literals.

var height = [9,8,7,3,6,5,2,4];
var objArr = height.map((h, index) => ({h, index}));

console.log(objArr);

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

Leverage express for proxying websocket connections

Currently, I am facing a situation where my data provider gives me stock prices through a TCP connection but only allows a static IP to access their service. Since I need to format the data before sending it to my front-end, I plan to utilize my express ba ...

Using JavaScript to locate and emphasize specific words within a text, whether they are scattered or adjacent

I need help finding a JavaScript code for searching words in a text using a form and a search button. I found one that works for multiple words in a row, but it doesn't work if the words are mixed up. What changes should be made to fix this issue? An ...

Sharing golang gin session with next.js

Utilizing the latest version of Next.js v14.2.3 and App Router. I am currently implementing cookie-based sessions from the gin-contrib documentation, in order to increase a session count. // Backend Golang code snippet ... cookieStore := sessi ...

Troubleshooting a ForwardRef issue in a TypeScript and React Native project

Encountering a ts error while using forwardRef. // [ts] Property 'forwardRef' does not exist on type 'typeof React'. const MyComponent = React.forwardRef((props: Props, ref: any) => ... An issue arises in React Native when the pare ...

Issue with Multiple File Upload Functionality in Dropzone.js + Laravel (Only allowing one file to be uploaded)

Looking for assistance in uploading multiple files using AJAX with Dropzone.js plugin. This is what I have implemented so far - HTML (view)- <div class="dropzone" id="add-slide-image"> </div> JS- Dropzone.autoDiscover = false; var myDropzo ...

Two liquid level divs within a container with a set height

I hesitated to ask this question at first because it seemed trivial, but after spending over 3 hours searching on stackoverflow and Google, I decided to give it a shot. The issue I'm facing can be found here: http://jsfiddle.net/RVPkm/7/ In the init ...

Issue persists with Angular 2 *ngFor functionality even after successfully importing CommonModule

After creating a feature module using the CLI, I imported the common module as shown below: import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { HomeComponent } from './home/home.compo ...

Error: The gulp-cssmin plugin encountered a TypeError because it attempted to read the property '0' of a null

I am attempting to condense my code, but I am encountering this error: D:\gulp-compiler\node_modules\gulp-cssmin\node_modules\clean-css\lib\selectors\extractor.js:66 return name.replace(/^\-\w+\-/, ...

I am encountering an issue where pagination is not functioning correctly while applying filters. Can anyone suggest a

I am currently experiencing an issue with my datatable. The result and pagination function correctly, however, when I apply a filter, the pagination does not adjust accordingly. This seems to be a common problem on this type of page.https://i.sstatic.net/p ...

What is the impact of Javascript variable scope in the context of "for...in..." loops?

Imagine you have a code snippet like this: dict = {"key":"elem"} for (var elem in dict){ someFunction(function(){ anotherFunction(dict[elem]); }) } Question: Is elem still considered as the temporary variable created in the for...in... s ...

The hidden absolute positioned div disappears once the sticky navbar becomes fixed on the page

Whenever my navbar reaches the top of the screen, the links in the dropdown menu disappear. I followed tutorials and examples from w3schools to build my webpage. Specifically: howto: js_navbar_sticky howto: css_dropdown_navbar This code snippet exempli ...

Navigating the complexities of integrating Rollup, ES modules, TypeScript, and JSX can be a challenging endeavor due to

Lately, I've been learning about the tools mentioned in the title. However, I've encountered some bumps along the way, so I'm turning to StackOverflow for help. My Requirements I need something like Rollup to pack my stuff For bare module ...

Passing onClick event to parent component during iteration in ReactJS

I am facing a challenge where I need to remove a row from a table upon a click event. I have managed to create an iteration and display a delete button, but I am struggling with passing the onClick event from the parent component to the child component in ...

Is there a way to restrict the number of line breaks in a multiline asp:TextBox control?

Is it possible to restrict a multiline asp:TextBox to only display content on 3 lines using either javascript or C#? ...

es-lint is issuing a warning about the presence of multiple modules within the node_modules directory that have names differing only in their casing

After reviewing all my import statements, I found that everything looks correct. The only unusual import I have is react-bootstrap, which I import as: import { Jumbotron, Button } from 'react-bootstrap'; I'm using the Jumbotron and Button ...

How to change a POST request to a PUT request using Express and keeping the

In my express app, I have set up two routes like this: router.post('/:date', (req, res) => { // if date exists, redirect to PUT // else add to database }) router.put('/:date', (req, res) => { // update date }) W ...

What does {``} denote in react-native programming?

During my participation in a collaborative project, I noticed that there is a significant amount of {' '} being used. For instance: <Text> {' '} {constant.Messages.PointText.hey} {this._user.first_name || this._user ...

Terminate a browser tab with the click of an HTML button

I'm facing an issue with my HTML button - I need it to close the tab upon clicking. Unfortunately, the common methods seem to no longer work on newer versions of Chrome and Firefox. I've tried using these two solutions but they did not work: & ...

The value of msg.member is empty following the messageReactionAdd event

Whenever someone reacts on my server, it triggers the messageReactionAdd event. However, I am encountering difficulty in retrieving the member object of the author of a message that someone reacted to: module.exports = async (client, messageReaction, user) ...

Caution: React detecting an active event listener on a scrolling-dependent 'touchstart' action

I am facing an issue with a React component that contains a Material-UI Slider. Whenever this component renders, I receive the following warning message: "Added non-passive event listener to a scroll-blocking 'touchstart' event. Consider marking ...