assigning a value to an index in an array will update all elements in the array

I'm encountering an issue with updating values in a complex JavaScript object that contains an array. Whenever I attempt to set the value for one attribute at a specific index, it ends up being applied to all items in the array.

Let's illustrate this with a simple example:

const obj = new Object();    
obj.arr = [];
obj.arr[0] = {pos:[0,0]};
obj.arr[1] = {pos:[0,0]};

If I try to assign values to attributes using specific indices:

obj.arr[0].pos = [10,10];
obj.arr[1].pos = [5,5];

The problem arises when the value [5,5] seems to be propagating to both items in the array. This results in:

console.log(obj.arr[0].pos) returning [5,5] and

console.log(obj.arr[1].pos) also yielding [5,5]

Although my actual object is more intricate, this simplified scenario conveys the essence of the issue...

Any suggestions or insights on how to address this?

Answer №1

When multiple variables/properties of an object point to the same value, they are considered sharing the same link.

The accuracy of the answer depends on the composition of your object.

var nested = {a:1};
var obj = {arr:[]};
obj.arr[0] = {pos:0, n:nested};
obj.arr[1] = {pos:0, n:nested};

obj.arr[0].pos = 1;
obj.arr[1].pos == 1; // false
obj.arr[0].nested.a = 2;
obj.arr[1].nested.a == 2; // true

Assigning identical array/object literals does not result in the same outcome.

var a = [0];
var b = [0];
b[0] = 1;
a[0] == 1; // false
b = a;
a[0] = 2;
b[0] == 2; // true

a = b = [0];
a[0] = 1;
b[0] == 1; // true

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

Transitioning create-react-app from JavaScript to Typescript

A few months ago, I began a React project using create-react-app and now I am interested in transitioning the project from JavaScript to TypeScript. I discovered that there is an option to create a React app with TypeScript by using the flag: --scripts-v ...

Exploring the functionalities of the Chrome Web Store with WebdriverJS

I am currently experiencing difficulties when testing the Chrome Webstore with my own node.js script and WebdriverJS. Every time I try to query the results using CSS selectors, I consistently receive "no such element" errors from the WebDriver Server. va ...

Clearing a textarea in jQuery

I'm experiencing an issue that I can't seem to resolve on my own. Any assistance would be greatly appreciated. My function designed to clear a textbox upon click doesn't seem to be working correctly: $(function() { $('textarea#co ...

Transferring an array to PHP using AJAX

In this coding scenario, I initialize my array: let myArray = []; Within a loop, elements are added to the array as follows: myArray.push($(this).data('id')); // Example: [1, 2, 3, 4] Subsequently, I transmit this data to PHP using AJAX throu ...

Error Type: expected string, instead of integer; Python

I have been attempting to create a Python code for calculating the Fibonacci sequence using memoization. Below is the code I have written: def fib(n, memo): if memo[n] is not None: return memo[n] if n == 1 or n == 2: result = 1 ...

inject a $scope object into a view when a button is clicked

Right now, I am using an array as a $scope object $scope.data { item1: "Value", item2: "Value Alt" } Every item corresponds to a form input with a default value. My goal is to create a new form from the same data set upon an ng-click event while main ...

How to dynamically populate a Vue multiple select dropdown with v-for loop?

I have been attempting to implement multi-select questions in Vue using v-for. The Select menu and its options are populated via JSON data. Unfortunately, I am facing difficulty in retrieving the selected results as expected. Whenever I select an option ...

What does it mean in Javascript when b1 is undefined while o1 has a value and is equal to b1?

Having some issues getting variables to work with drop down options on a page. At first, I couldn't even extract a value from the function but managed to do so by removing "var" from o1. Strange thing is, when I type o1 into the js console on chrome i ...

Adjust the width of the element to match the size of the image within

My webpage features an image along with some accompanying metadata that I want to be centered on the page. I want the div holding the metadata to be the same width as the image. Here's an example: Unfortunately, I am unable to determine the image&apo ...

JavaScript group by first letter issueI am facing a problem when trying

Having an issue with my code that needs to group contacts by first letter: A. ADRIAN ANDREI ANGEL B. BENY BORRIS Z. ZEYN etc. The current code is not displaying the groups correctly. I want to list each contact under its initial letter. Below is ...

How can I cycle through an ArrayList containing nodal values of an array?

How can I efficiently iterate through an ArrayList containing arrays as its value to display all the array components in each node on a single line? Here's an example: ArrayList<String[]> arr_list = new ArrayList<String[]>; String array ...

Managing redundant asynchronous data in AngularJS

Imagine this scenario: In your AngularJS application, a user is spamming input which triggers numerous asynchronous data calls on the backend. This results in constant changes to the displayed data as each fetch request completes. Ideally, we want the fina ...

Using AngularJS to showcase an organized $http reply in a segment of a template

I have a current project where I am looking to organize responses by category and subcategory using Angular. My controller code currently appears as follows: function($http, $stateParams) { let vm = this; $http({ method: ...

The `value` attribute in the Dropdown component should be an array if the `multiple` option is enabled. The current type received is a `[object

Hey, I'm encountering an issue. The Dropdown component is throwing an error telling me that the value must be an array when multiple selection is enabled. The type received is: [object String]. Check out my code snippet here: https://codesandbox.io/ ...

Error with JavaScript slideshow The slideshow using JavaScript seems to

I'm currently utilizing a script from the WOW Slider (free version) that looks like this: var slideIndex = 0; function showSlides() { var i; slides = document.getElementsByClassName("mySlides"); dots = document.getEle ...

An array of objects, where each object contains an array populated with variable names instead of their corresponding values

I have created a custom object class SalesReportObject { public $eventname = ""; public $v_firstname = ""; public $v_secondname = ""; public $soldStock = array(); function Push($productname, $soldquantity) { $soldStock[$pro ...

Retrieving the specific coordinates from a sole contour identified through the findcontours function in opencv with the use of python

Below is the code I used to store coordinates (x,y) found by cv2.findcontours in OpenCV with Python. I randomly selected a contour: c=contour[6] Now I need to extract the x and y values into separate arrays for further operations. Numpy arrays are typi ...

Combining Two Arrays in PHP to Create a Table with the First Array displayed vertically and the Second Array

I am trying to achieve a specific layout in the view. https://i.sstatic.net/7rTxC.png The following is an example of the array structure: Array ( [0] => Array ( [car_id] => ferarri [total] => 15 ) [1] => Array ( [car_id] => lamborgini [t ...

extract element from a string with the help of jquery

When using AJAX to request HTML from a page, the process involves sending a request like this: function getHTML() { //set ajax call var options = { url: '/Controller', type: 'GET', d ...

Tips for integrating filters in a Rails application without needing to reload the page

Looking for advice on implementing a filter feature in my Rails application. I want to have the ability to filter results and see them update instantly on the same page, similar to travel websites like skyscanner and liligo. When you select a checkbox on ...