The Angular.copy() function selectively copies properties and does not duplicate everything

Exploring a function within a service:

$scope.addPeriod = function(newPeriod) {        
        if(newPeriod.from !== '' && newPeriod.until !== '') {           
            var index = $scope.newPeriods.indexOf(newPeriod);       
            $scope.newPeriods.splice(index, 1); 
            $scope.setHolidayEditions(newPeriod);


            console.log("Check period");
            console.log(newPeriod); // state 1: object newPeriod is as expected, it contains holidayEdtions

            console.log("Check period copy");
            console.log(angular.copy(newPeriod)); // state 2 : object newPeriod is missing the holidayeditions!
            $scope.periods.push(angular.copy(newPeriod)); //original code
            //some more logic irrelevant to the question
        }
}

The issue lies with the angular.copy() method. The structure of the newPeriod object is as follows:

it includes a "from" date and an "until" date, along with an array of magazine objects. In addition, there is the $scope.setHolidayEditions (newPeriod) function, which appends an array of edition objects to each magazine. This function operates correctly, evident from the console output. In the original code, the period is then pushed into an array of periods, which is ultimately displayed on the screen. Presumably, angular.copy() was used to prevent reference issues.

However, the angular.copy() function seems to overlook copying the freshly created editions array within the magazine objects. Is there a rationale for this behavior?

This is essentially what occurs in the service function:

There exists an object named newPeriod, structured like so:

{
  from:"02/10/2015", 
  until:"09/10/2015",
  magazines: [
           {title:"some title", number:"some number", code:"magazineCode"},
           {title:"other title", number:"other number", code:"magazineCode2"}
  ]
}

post the execution of $scope.setHolidayEditions(newPeriod), the object transforms into:

    {
          from:"02/10/2015", 
          until:"09/10/2015",
          magazines: [
                   {title:"some title", number:"some number", code:"magazineCode", holidayEditions:["date","date","date"]},
                   {title:"other title", number:"other number", code:"magazineCode2", holidayEditions:["date","date","date"]}
          ]
}

Nevertheless, after the usage of angular.copy(newPeriod), the object reverts back to its initial form:

 {
      from:"02/10/2015", 
      until:"09/10/2015",
      magazines: [
               {title:"some title", number:"some number", code:"magazineCode"},
               {title:"other title", number:"other number", code:"magazineCode2"}
      ]
    }

It's perplexing how the angular.copy() operation fails to include the holidayEditions array within the magazines. Any insights on this puzzling behavior?

Answer №1

It appears that I faced the same issue some time back, and after careful consideration (among other factors), I opted to utilize lodash, which offers a specific function to address this very problem:

_.cloneDeep(value, [customizer], [thisArg])

This function is designed to create a thorough copy of the provided value. If a customizer is specified, it will be used to generate the cloned values. In cases where the customizer does not return any value, cloning will be managed by the method itself. The customizer is associated with thisArg and called with a maximum of three arguments: (value [, index|key, object]).

Please Note: This approach draws inspiration from the structured clone algorithm. Properties that can be enumerated in arguments objects and objects formed by constructors aside from Object are replicated to basic Object objects. For unclonable entities like functions, DOM nodes, Maps, Sets, and WeakMaps, an empty object will be the result.

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

Getting the value from a .sh (Shell Script) file in React: How to do it?

There is a .sh file that contains the following code: echo "Hello" This code produces the output: Hello The question at hand is: I am trying to extract the output from the .sh file and integrate it into my React application. After exploring various ...

Tips for creating nested maps of an array without triggering the key prop warning

I am dealing with an array of data: const arr = [ { title: "title1", content: [ { id: "home", name: "Home", }, { id: "services", name: "services", ...

Passing object attributes to a modal in AngularJS

I am trying to figure out how to pass a complete object to my modal so that I can view all of its attributes there. Currently, the items I have look like this: $scope.items = [{ Title: title, Id: id }] On my html page, I am using 'ng-repeat' as ...

Error 504: The timeout issue occurred during an ajax call

When I make an ajax call to process a large amount of data and then reload the page upon success, I encounter a 504 Gateway Timeout error. The ajax call is initiated with the following parameters: $.ajax({ type:'POST', cache:false, a ...

Enhance Bootstrap typeahead to accommodate multiple values

I have a basic typeahead setup for searching city names. However, upon selecting a city, I also need to retrieve its latitude and longitude in order to send that data to the backend. $('.typeahead').typeahead({ minLength : 3, source : ...

Remove any JSON objects in JavaScript or AngularJS that match another JSON object

JSON A ['711','722','733','744'] JSON B [{pid: 711, name: 'hello'},{pid: 733, name: 'world'}, {pid: 713, name: 'hello'},{pid: 744, name: 'hellosdaf'}] I am attempting to remo ...

What method is most effective for duplicating objects in Angular 2?

Is it just me, or does Angular 1.x have methods on the global angular object like angular.copy and angular.shallowCopy that are missing in Angular 2? It seems like there is no equivalent version in Angular 2 documentation. If Angular 2 doesn't plan on ...

Notify when the button value changes to "submit"

I recently added a jQuery form wizard to my website. I want users to receive an alert in JavaScript when they reach the end of the form. To achieve this, I inserted a simple JavaScript code at the beginning of my page within <head>..some code</hea ...

Is there a way to transform this pledge back into a JSON array format?

My goal with this code is to retrieve a JSON array from my server. var students_list; const library_address = 'http://localhost:17330' async function fetchData(param1, param2) { if(param1 == 'getdata') { const response ...

Switch from using fetch to utilizing axios for making API requests

I used fetch for a 'get' request, but now I want to switch to axios. Can someone please help me convert this code to use axios instead? More details: I am fetching an image and using the blob method to display it to the user. I would like to ach ...

Is it possible to utilize both href and ng-click in Angular.js?

Here is a text box: <input type="text" ng-model="SearchText" > And also, a link: <a href="#logout" ng-click="SearchText=''">Logout</a> I am trying to make both actions work in the above hyperlink. The ng-click should clear t ...

What methods are available for identifying critical points within a 2D array using Python?

My task involves analyzing a large (960,960) array to identify critical points in order to determine local extrema. Despite attempts using np.diff and np.gradient, I have encountered challenges and uncertainty regarding the appropriate function. While np ...

Recreate body content with JQuery Mobile

I've been attempting to duplicate the entire HTML content within the tags. However, even though the appearance on screen is correct, none of the links are functioning.</p> <p>To view the fiddle, click here: [Here is a fiddle][1]</p> ...

What is the best method for handling and analyzing error objects within a catch statement following an API request?

When working with an API, dealing with complex error objects is a common occurrence. Depending on the specific API, the error messages can be quite informative and sometimes you may want to directly display them to the user. However, the challenge lies in ...

Ways to access and delete the canvas using ref steps?

Having a canvas in a react component, I utilized react refs to access the node and implemented a destroy() method. However, I encountered an error: TypeError: canvasRef.current.destroy is not a function How can we properly access the node (canvas) using r ...

Convert XML to an HTML table in real-time as new elements are introduced

Currently, I have JSON and AJAX code that fetches XML data every second, which is working smoothly. When I added an XML element, it automatically gets added to an HTML table. The issue arises when I call the function every 3 seconds; the page refreshes due ...

What is the reason for Jquery AJAX appending additional path to the relative path?

I am encountering an issue with the following code snippet $.ajax({ url: "search/prefetch", success: function (data) { $(".result").html(data); alert("Load was performed."); }, dataType: "json" } ...

What is the best way to conceal the HTML video controls for multiple videos displayed on a single webpage?

I have a web page that displays a collection of movies generated using a PHP foreach loop. The code snippet looks like this: foreach ($movies as $movie) { $pos = strrpos($movie, '/'); $id = $pos === false ? $movie : substr($movie, $pos ...

What is the best way to retrieve data attributes from multiple div elements that share the same class name?

I have multiple div elements with the same class name. I want to extract the data attribute from these div's. I have tried some code and managed to get the result. However, I am unsure if this is the best approach for retrieving data("cartid"). Any as ...

Issue with updating overall expenditure functionality

I'm currently in the process of developing a straightforward shopping cart with the help of simpleCart.js. Up until now, I've managed to successfully showcase items, add them to the basket, and proceed to checkout. However, my next challenge inv ...