What is the reason for the original list being affected when the cloning list is created using a

I am trying to convert an object inside an array into a string using the code below. However, I can't seem to understand why it's affecting the original array. I thought that 'slice' was supposed to clone the array?

var cloned = $scope.selected.items.slice(0);
cloned.forEach(function (cluster) {
  cluster.status = cluster.status.name;
})
ObjToPost.MO = cloned;
console.log("consoling the cluster list", ObjToPost.MO);
console.log("consoling the original cluster list", $scope.selected.items);

Upon checking both arrays, they seem to be identical.

Answer №1

According to MDN's documentation on the Array.prototype.slice method,

The slice() function creates a shallow copy of part of an array in a new array object.

The key concept here is "shallow copy", where a new Array is generated with elements pointing to the same objects as the original.

In this scenario, despite slicing, both the initial and copied arrays have elements that reference the same cluster objects in memory.

Original                        Cloned
+-----+                        +-----+
|  0  |--> Cluster Object 1 <--|  0  |
+-----+                        +-----+
|  1  |--> Cluster Object 2 <--|  1  |
+-----+                        +-----+
|  2  |--> Cluster Object 3 <--|  2  |
+-----+                        +-----+

As all corresponding elements point to the same objects, changes made through one array will also affect the other.

Note: For deep copying, referring to solutions in this thread may be more appropriate.

Answer №2

As explained by @thefourtheye, you are making a shallow copy of the array. To make a deep copy of the array elements and change the status, you can utilize Array.prototype.map along with angular.merge():

ObjToPost.MO = $scope.selected.items.map(function(cluster) {
    return angular.merge({}, cluster, { status: cluster.status.name }); // creating a deep copy of each element, and updating status with status.name
});

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

Serving static files in Next.js with specific extensions without triggering a download

I'm facing an issue where I need to serve the stellar.toml file in domain/.well-known/stellar.toml with the content type as text/plain. The current configuration works only when the stellar file is saved without an extension. It is essential for me t ...

Error: Koa.js framework is unable to find the "users" relation in the Sequelize database

I am currently facing an issue while attempting to establish a relationship between two tables, 'user' and 'accessToken'. The error message I am encountering is hindering the process. Below are the models in question:- User model:- ...

Utilizing JavaScript regex to remove substrings that contain parentheses

I am working with a string variable named myString that includes some unwanted content towards the end: var myString = 'The sentence is good up to here foo (bar1 bar2)'; var toBeRemoved = 'foo (bar1 bar2)'; I am looking for the best w ...

What is the process for making an Ajax request in Rails?

I'm attempting to send a variable through jQuery using the POST method, saving it in a controller, and then utilizing that same variable in Rails HTML to query a table. It seems like the variable isn't being passed to the controller. jQuery: v ...

Replace the transformation matrix of a three.js object/mesh entirely

Creating a new object in three.js In order to create a three.js mesh object, follow these steps: var geometry = new THREE.BufferGeometry(); var standardMaterial = new THREE.MeshStandardMaterial( {/* inputs */ } ); var mesh = new THREE.Mesh( ...

Avoid having gulp's uglify plugin remove es6 code

I've encountered an issue while using gulp babel to compile es6. It seems that uglify is stripping out my es6 code completely. Strangely, I'm not receiving any errors in my command line during the process. Have you faced this problem before? Any ...

Utilizing JQuery AJAX to Submit a JSONP Form with File Attachments

I have been working on implementing a contact form for our clients who create websites with their own domains through us. As part of our services, we provide hosting and a web editor to help them build their websites. The contact form they include on their ...

What is the reason behind the brute force method for finding the maximum sum subarray having a time complexity of

The concept of finding the maximum subarray sum is a well-known issue within the realm of computer science. There exist at least two potential solutions: One method involves brute force, where all possible subarrays are calculated to determine the maximu ...

Field Enchanted - JQuery Plugin

A TypeError was caught: Object #<Object> does not contain the method 'easeOutCubic' is being output in the console, and it seems to be related to a JQuery plugin known as Decorated Field. Upon inspecting the contents of the zip file, I cou ...

Manipulate object position using Aframe and three.js

I'm working on developing a game using A-frame. I'm trying to add a shooting effect by incorporating a gun model that follows the user's cursor. I've coded a click event so that an object moves in front of the gun and follows the direct ...

The Angular Reactive Forms error message indicates that attempting to assign a 'string' type to an 'AbstractControl' parameter is invalid

While attempting to add a string value to a formArray using material forms, I encountered the following error message: 'Argument of type 'string' is not assignable to parameter of type 'AbstractControl'.' If I try adding a ...

What is the best way to use createElement in JavaScript to insert <p> and <span> elements within a <div>?

I am currently experimenting with generating sentences accompanied by draggable text boxes. To achieve this, I intend to construct the following HTML structure using JavaScript exclusively: <div> <p>Data1<span class = "smallBox droppabl ...

After the "div" tag comes the magic of AJAX, PHP, and JAVASCRIPT, replacing

My Ajax implementation is successfully displaying the selected content on a div, but unfortunately, everything that comes after the div is getting replaced by this output. I am unsure of why this is happening and how to resolve it. If you have any insigh ...

Is it possible to utilize index as a unique identifier for React Components?

In my React application, I have a list with the following requirements: Only new elements are added to the end of the list. When an element is removed, it is always the last element in the list. Considering these conditions and the fact that I do not ne ...

The AJAX request is not successful because it is encountering a ReferenceError due to attempting to assign a value to an

My attempt to trigger a modal using dynamic data from the database with an AJAX function is encountering issues. Upon clicking the button to open the modal, I encounter this error: ReferenceError: assignment to undeclared variable PostRPC in category.ph ...

Rendering a texture onto a 1x1 model in three.js

Hey there, I'm trying to apply a texture (around 300x300) to a simple box model using a box model. Here's the code I'm currently using to load the material: new THREE.MeshBasicMaterial( { map: new THREE.TextureLoader().load( 'material ...

Tips for organizing and nesting form data

Can I format my data in JSON like this: { attachments: { file: [ { name: 'pic1.jpg' }, { name: 'pic2.png' } ], username: 'Test', age: 1 } } Is it achievable us ...

The value remains constant until the second button is pressed

I have a button that increments the value of an item. <Button bsStyle="info" bsSize="lg" onClick={this.addItem}> addItem: addItem: function() { this.setState({ towelCount: this.state.towelCount - 2, koalaCount: this.state.koalaCount + 2 ...

Choose each day's time slot on the jQuery FullCalendar version 2.x

The code snippet below is a segment of the code generated by the FullCalendar jQuery plugin version 2. It has undergone some changes from version 1.x in terms of the classes it utilizes. <div class="fc-slats"> <table> <tbody> ...

Scala's multidimensional array functionality can be further enhanced through the use of the

I am faced with a challenge involving two different arrays: val one = Array(1, 2, 3, 4) val two = Array(4, 5, 6, 7) var three = one zip two map{case(a, b) => a * b} While this solution works for the given arrays, my problem has evolved. Now, I have a m ...