Prevent the creation of references to objects passed as function parameters in a separate list

I'm facing an issue with modifying items from an array and adding them to a new list of objects.

The problem arises when I make changes to the item in the new list, it also reflects those changes in the original array. It seems like there is some reference linking the new and original items together.

To replicate this problem, please refer to the Controller's comments and run the code as "Full page":

angular.module('app', [])
  .controller('MainCtrl', function($scope){
    
    $scope.items = [
      {id: 1, name: 'item 1'},
      {id: 2, name: 'item 2'},
      {id: 3, name: 'item 3'}
    ];
    
    $scope.newItems = {
      "hello": "World!"
    };
    
    //Function to add selected item object to $scope.newItems
    $scope.addItem = function(item){
      $scope.newItems.item = item;
    };
    
    //Add color property to the previously added object
    $scope.addColor = function(clr){
      $scope.newItems.item.color = clr;
    };
    
    //Although no changes are made to $scope.items, modifications to objects in the new list reflect on the original object.
    
    //For testing purposes
    $scope.$watch('items', function(newValue, oldValue){
        if (newValue !== oldValue) {
          $scope.showProblem = true; //this should NEVER occur
        }
    }, true);
    
  });
<link data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="12707d7d66616660736252213c213c27">[email protected]</a>" data-semver="3.3.5" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="24454a43514845564e5764150a100a1d">[email protected]</a>" data-semver="1.4.9" src="https://code.angularjs.org/1.4.9/angular.min.js"></script>

<body ng-app="app">
  <div ng-controller="MainCtrl">
    <div class="alert alert-danger" ng-if="showProblem">
      <strong>UNDESIRED BEHAVIOR:</strong> Original items array has been modified.
    </div>
    
    <ul class="list-group">
      <li ng-repeat="item in items track by item.id" class="list-group-item">
        {{item.name}}
        <a ng-click="addItem(item)" class="badge btn btn-sm btn-success" ng-if="!newItems.item">Add item</a>
        <a ng-click="addColor('red')" class="badge btn btn-sm btn-success" ng-if="newItems.item.id === item.id">Add color property</a>
      </li>
    </ul>
    
    <div class="panel panel-default">
      <div class="panel-body">
        <h3>Original item array</h3>
        <pre>{{items | json}}</pre>
      </div>
    </div>
    <div class="panel panel-default">
      <div class="panel-body">
        <h3>New item list</h3>
        <pre>{{newItems | json}}</pre>
      </div>
    </div>
  </div>
</body>

Answer №1

Great explanation - you nailed it! When it comes to object assignments, they are just references. Let's delve into an example:

let car = { make: "Toyota" }
let newCar = car;

newCar.make = "Honda";
console.log(car.make); // Honda;

Both car and newCar are pointing to the same object - changing one will affect the other. In Angular, there is a handy method called angular.copy(obj) which clones the object without sharing the reference:

$scope.newVehicle.car = angular.copy(vehicle);

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

Unable to display the Error 404 Component within a nested Component using React Router

When attempting to display the Error component if no matches are found, I encountered an issue - selecting a non-existing route only leads to a blank page. In the example, the Main component adds a sidebar menu and renders all its children inside it. If ...

Validating Two DateTime Pickers as a Group with Javascript in asp.net

How to Ensure Group Validation of Two DateTime Pickers Using JavaScript in ASP.NET ...

Is there a way to retrieve the request URL within the validate function of the http strategy?

Is it possible to access the context object present in guards within the validate method of my bearer strategy, by passing it as an argument along with the token? bearer-auth.guard.ts: @Injectable() export class BearerAuthGuard extends AuthGuard('be ...

Efficient method for deleting a specific item from a JSON object in React.js

Within the REACT JS framework, I am managing a JSON object in the state component "myrecords". The items within this object are organized by their respective Company Names and have the following structure: { "Master Automotives": [ { ...

Issue arose when attempting to utilize the API key as an environmental variable within the Butter CMS library while working within the async

After migrating my website from Drupal to Vue, I decided to enhance the SEO performance by transitioning it to Nuxt. However, I am encountering difficulties in setting and utilizing a private API key as an environment variable in a component with the Butte ...

Progressively modifying related elements over time intervals

I have a specific list of p elements in my HTML code that I need to modify sequentially with a time interval of 1 second. Here is the HTML: <p>Changing first sentence!</p> <p>Second sentence ready!</p> <p>Third one coming up ...

Delete elements with identical values from array "a" and then delete the element at the same index in array "b" as the one removed from array "a"

Currently, I am facing an issue while plotting a temperature chart as I have two arrays: a, which consists of registered temperature values throughout the day. For example: a=[22.1, 23.4, 21.7,...]; and b, containing the corresponding timestamps for eac ...

The Javascript Ajax loader gif is malfunctioning

I'm currently working on creating an Ajax loader gif using XMLHttpRequest. When I type something in the input field, a list of different words appears. This technique is commonly used in search engines as you type in the search box. However, I am als ...

What are the steps to clipping a canvas using CSS clip-path?

When it comes to clipping a canvas, there are multiple methods that can be used. One way is to create a path with getContext('2d') and set globalCompositeOperation. Another method involves using -webkit-clip-path or clip-path, though the latter m ...

Using Selenium Webdriver to target and trigger an onclick event through a CSS selector on a flight booking

I've been running an automation test on the website . When searching for a flight, I encountered an issue where I was unable to click on a particular flight. I initially tried using Xpath but it wasn't able to locate the element when it was at th ...

Exploring an array of objects to find a specific string similar to the one being

I recently developed a TypeScript code snippet that searches for objects in a list by their name and surname, not strictly equal: list = list.filter( x => (x.surname + ' ' + x.name) .trim() .toLowerCase() .sear ...

Socket.io-powered notification system

I'm currently in the process of developing a notification system for my Events Manager Website. Every time a user is logged in and performs an action (such as creating an event), a notification about the event creation should be sent to other user ...

The authentication protocol, Next Auth, consistently provides a 200 status response for the signIn function

I ran into a challenge while building my custom login page using Next Auth. The issue arises when I try to handle incorrect login data. If the login credentials are correct, I am able to successfully send JWT and redirect to /dashboard. However, when the l ...

The operation of Ajax can be intermittent, as it may run at

I'm encountering an issue with my ajax code. I am adding data from my database and attempting to refresh a div element. It seems to work sometimes but not consistently. Why is that? Here's the problem - I have a function called addtoqueue. Insid ...

Using Angular routing without relying on a web server to load templates

Can templates be loaded in Angular without a web server? I came across an example here: https://groups.google.com/forum/#!topic/angular/LXzaAWqWEus but it seems to only print the template paths instead of their content. Is there a functioning example of t ...

Starting service without dependency injection in Angular

I am facing an issue with my list of services (referred to as "handlers") and one manager, which is also a service. I need all handlers to register themselves with the manager. However, I have encountered a problem - no one is injecting these handlers, so ...

Guidelines on launching an ionic 4 modal using routes

How can I open a modal using routes? I attempted the following approach, but it did not work as expected: ngOnInit() { this.launchModal(); } async launchModal() { const modal = await this.modalController.create({ component: AuthPasswordR ...

Having issues with getting Bootstrap to function properly in my create-react-app

I've been attempting to use traditional Bootstrap instead of react-bootstrap to render my React component, but I can't seem to get it right. I've installed Bootstrap via npm and included the CDN links and scripts as well. Despite trying vari ...

Get back a variety of substitutions

I have a variety of different text strings that I need to swap out on the client side. For example, let's say I need to replace "Red Apple" with "Orange Orange" and "Sad Cat" with "Happy Dog". I've been working on enhancing this particular ques ...

What is the best way to display a nested JSON object structure?

{ "Title": "Jurassic Park", "Year": "1993", "Rated": "PG-13", "Released": "11 Jun 1993", "Runtime": "127 min", "Genre": "Action, Adventure, Sci-Fi", "Director": "Steven Spielberg", "Writer": "Michael Crichton, David Koepp", "Actors": "Sam ...