JavaScript reference problem when copying

Initially, I create a raw array by using the following initialization:

$scope.rawUsers = angular.copy($scope.users);

Subsequently, I make modifications to the data like so:

function filterUsers(searchString, onlyMine) {

$scope.users = [];

_.find($scope.rawUsers, function (itm) {

    var groups = [];


    if (onlyMine) {
        if (!itm.IsMine)
            return;
        var hasGroup = false;
        _.find(itm.Groups, function (group) {



            if (lowercaseGroups.indexOf(searchString) != -1) {
                hasGroup = true;

                groups.push(group);
            }

        });

        if (hasGroup) {
            itm.Groups = groups;
            $scope.users.push(itm);
        }

    } else {
        if (itm.IsMine)
            return;

        $scope.users.push(itm);
    }

});


}

Is there a way to prevent the loss of the original value in this process?

Answer №1

To make a duplicate of the array $scope.users without any reference, you can utilize the spread syntax as shown below:

$scope.rawUsers = [...$scope.users];

The spread syntax allows an iterable, such as an array expression or a string, to be expanded where elements are expected, enabling you to create a new copy of the array.

The spread syntax can expand arrays, strings, or object expressions in places where elements or key-value pairs are expected, providing a convenient way to create copies or expand data structures.

If you prefer using angularjs functions, you can achieve the same result by using angular.copy() to create a deep copy of the source object or array. The following code snippet demonstrates this:

$scope.rawUsers = angular.copy($scope.users);

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

Encountered an Error: UpdateCommand is not a valid constructor - AWS SDK v3 when running unit tests with Jest in Node.js

Every time the unit test reaches the point where it calls the UpdateCommand from @aws-sdk/lib-dynamodb, I encounter an error saying "TypeError: UpdateCommand is not a constructor". I suspect that there might be an issue with the mock. I'm unsure of ho ...

Encountering a ReferenceError stating that the window object is not defined while building a React Leaflet application

In my upcoming nextjs project, I've incorporated react-leaflet. It behaves flawlessly in dev mode. However, upon attempting to build the project, it throws a ReferenceError: window is not defined. Despite setting ssr to false in dynamic, the error per ...

AngularJS experiencing issues with Bootstrap multiselect functionality

I am currently integrating bootstrap-multiselect into my AngularJS application. To do this, I've included the following scripts in my master page (index.html). <script src="/bower_components/jquery/dist/jquery.min.js"></script> <scrip ...

Every time I try to create a new React app, I consistently run into the same error

I keep encountering this error every time I try to create a React app using create-react-app. ...

The emission from Socket.io is originating from the recipient's browser without being transmitted to the sender's browser

Hey there, I'm fairly new to socket.io and not completely sure if what I'm doing is the standard way, but everything seems to be working fine so I guess it's okay. I've been working on a chat application where messages are stored in a d ...

How can refs be applied effectively in React applications?

I've been thinking about the role of refs in React and how they can address certain challenges for developers. However, I have found that the explanations provided in the React documentation are not very clear, and there seems to be a lack of helpful ...

Can someone suggest a method for deciphering hexadecimal code used in JavaScript?

How can I gain an understanding of this code and convert it into simple javascript? Can someone assist me in deciphering the code or transforming it back to its original script? If someone obfuscated the javascript, what type of method should we use to de ...

Ways to remove unnecessary spaces from a JSON Object

I have a generic ajax.post method that takes in data from a function parameter. I'm looking to trim the data properties within the function. Here's the current code snippet: function PostToServer(options) { var defaults = { 'url ...

How to delete a specific key-value pair from an object in React.js

There is an object stored in the state: this.state = { selectedValue: {} } Now, I am adding a property to this object as follows: if (e.currentTarget.checked) { this.setState({ selectedType: { ...this.state.selectedType, ...

Issue with the iteration process while utilizing Async.waterfall in a for-loop

This snippet may seem simple, but it represents a real issue in my current code base. When attempting to log the index of a for-loop within an async.waterfall function, I am encountering a peculiar situation where the index value is 2 instead of expected ...

What steps can be taken to proceed with the promise chain following a retry attempt

When using restangular to make multiple calls to the backend, I encountered an issue where subsequent requests are dependent on the result of the first call. To address this, I attempted to implement retry logic to ensure that follow-up requests are execut ...

Limiting the ability to pan to a single globe within the Google Maps API

I need help with restricting panning on a Google Maps API map to just one globe. By default, the map allows continuous panning east/west, causing it to repeat endlessly. I found a solution by henningj in response to this question var allowedBounds = new g ...

What is the memory allocation for null values in arrays by node.js?

Continuing the discussion from this thread: Do lots of null values in an array pose any harm? I experimented with node.js by doing this: arr=[] arr[1000]=1 arr[1000000000]=2 arr.sort() However, I encountered the following error: FATAL ERROR: JS Alloca ...

Error in Next.js 11: Unable to access property 'canonicalBase' as it is undefined

Encountering an issue after upgrading from Next.js version 10.0.2 to 11.0.1. Since the update, I am unable to initiate a project due to the following error: Cannot read property 'canonicalBase' of undefined In my _app.tsx file, the Next imports ...

The Modal Component remains unchanged despite being connected to useContext for data, as the Array is being modified through the useReducer Hook

In search of an elegant solution, the title speaks for itself - I am on a mission to create a practice food order App (consider me a novice in this field). This App boasts a Cart feature where users can add items for ordering. The nav-bar conveniently disp ...

Node.js and Express: Delegate routes to different endpoints for handling by the Single Page Application, instead of just the root route

I have my node.js/Express server configured to host my Vue.js single page application from the root URL path (localhost:3333) within the public folder. When navigating through my app, everything works smoothly thanks to the vue.js History API handling all ...

Invoking functions from controllers to mongoose schema module in Node.js

Greetings everyone, I am fairly new to working with Node.js so let me share my current dilemma. I have set up a mongoose schema for handling comments in the following structure: const mongoose = require("mongoose"); const Schema = mongoose.Schema; const ...

What is the best way to import a TypeScript file in index.js?

I've recently developed an application using the react-express-starter template. I have a "server" directory where the backend is created by nodejs, containing an index.js file: const express = require('express'); const app = express(); c ...

Using jQuery to eliminate the 'disabled' attribute from CSS

After using the .val() method to enter data into a text box, I noticed that when trying to click "add", the button appears disabled. <input class="btn-primary action-submit" type="submit" value="Add" disabled=""> If I manually type in text, the dis ...

developing a dynamic map with javascript

In the image provided, my concept is for it to initially be without a green tint. However, when the user hovers over specific areas, they would turn green and become clickable links. There are multiple areas in the image, with this being just one example. ...