Is there a way to make changes to a specific array without altering the original base array?


mapConfig(config: IConfigItem[], dataModel: IDataModel): IConfigItem[] {
    return config.map(c => {
      const entries: [string, string][] = Object.entries(c);
      entries.forEach(e => {
        const configValue = e[0];
        const configKey = e[1];
        if (configKey in dataModel) {
          c[configValue] = dataModel[configKey];
        }
      });
      return { ...c };
    });
}

Within my service class, there is a function called `mapConfig` which I am invoking from an Angular component.


const configCopy = [...this.config];
const dataModelCopy = { ...this.dataModel };
const mappedConfig: IConfigItem[] = this.loader.mapConfig(
  configCopy,
  dataModelCopy
);

To prevent the base object `this.config` from being modified, I created a copy of it and passed it to the `mapConfig` function. However, despite this precaution, the base object `this.config` still gets updated. I'm uncertain about what I might be doing wrong.

Answer №1

When using destructuring, it performs a shallow copy of objects. This means that inner objects will remain the same for both the copied and original objects. To achieve a deep cloning, you will need to implement a different approach.

An easy (but not necessarily the best) method is to stringify the original object:

const configCopy = JSON.parse(JSON.stringify(this.config));

Learn more about how to deep clone in JavaScript here

Answer №2

One way to achieve this task without any mutation is by following a similar approach:

modifyConfig(configuration: IConfigurationItem[], modelData: IModelData): IConfigurationItem[] {
    return configuration.map(configItem => {
        const itemEntries: [string, string][] = Object.entries(configItem);
        const entriesToReplace = itemEntries.filter(([value, key]) => key in modelData);

        const replacedEntries = entriesToReplace.map(([value, key]) => ({
            [value]: modelData[key]
        }));

        return {
            ...configItem,
            Object.fromEntries(replacedEntries)
        };
    });
}

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

bootstrap5 is unable to transform an undefined or null value into an object

Struggling to implement a new modal using Angular 11 and Bootstrap 5, encountering the following error: ERROR TypeError: Cannot convert undefined or null to object at Function.keys (<anonymous>) at Object.getDataAttributes (bootstrap.esm.js:8 ...

Tips for making Nav.Link have equal width in React Bootstrap

Looking for a way to make Nav.Link components the same width? <Navbar bg="dark" variant="dark" fixed="bottom"> <Nav className="me-auto"> <Container> <Ro ...

Getting JSON data from an Angular JS controller can be achieved by utilizing the built-in

My user login function includes a method called logincheck, which takes in parameters and sends a request to the server. Upon success, it redirects the user to the dashboard with the member ID. this.logincheck = function(log) { var pa ...

Unable to retrieve data from the array

I am encountering an issue while trying to fetch data from an array, as I keep receiving undefined Please refer to the image for a visual representation of my problem. I'm not sure what I might be overlooking, so any help would be greatly appreciate ...

Angular 6 - Assigning string value to a variable when a click event occurs

I want to store the text of a click event in a variable. Here is the current code I am using: <th (click)="sortedColumn = clickValue">Ask Price</th> When a user clicks on the table header, I need it to save the value "Ask Price" in t ...

What is the best way to solve the Hackerrank Binary Tree problem using TypeScript and output the

Here is the coding challenge from Hackerrank: Given a pointer to the root of a binary tree, you are required to display the level order traversal of the tree. In level-order traversal, nodes are visited level by level from left to right. Implement the fun ...

Modify ngb-datepicker tooltips language

I have developed a multi-language application that utilizes a customized NgbDatePickerI18n: @Injectable() export class CustomDatepickerService extends NgbDatepickerI18n { constructor(private translateService: TranslateService) { super(); ...

What is the best way to verify if the text values of a collection of DOM-nodes in an array match a specific string

My objective is to validate if all names in an array are equal to e2e. I have a set of objects generated using protractor's element.all(by.css(...). The next step involves confirming if any element within the array has a text value that differs from m ...

Using Javascript and jQuery to locate and remove a specific value from an array within the remaining values of the

Seeking assistance with organizing array values that may contain duplicated or appended strings. Each value could potentially build upon the previous one. For example: [0] => This is a string. [1] => here's another string. This is a string. [2 ...

Creating a Typescript version of the mongodb project aggregation functionality

Present scenario: I am currently working on creating a type-safe wrapper for the node-mongodb driver. I am facing challenges in determining the return type for the project aggregation stage. Feel free to check out the TypeScript Playground here class Base ...

What is the best way to describe a model with a complex JSON structure in Angular 2 using TypeScript?

My model has the properties listed below: { Name:String, Id:Number, Store:{ Name:String, City:String, State:String } } What is the best way to define a model with this structure in Angular 2 using TypeScript? ...

Challenges with JArrays

Having issues with JSON Parse and Jarray.Length. The goal of this app is to: metin variable serves as the search string. For example, if I input "DDDDDD", the SOFTWARE will search in the JSON file for "DDDDD" and display DDDDD's features on the consol ...

Issue with nested array date comparisons in mongo not resolving

I am working with a collection model that has the following schema: { "id":"122HSHDJS2333222222", "name":"Item1", "image":"", "is_deleted":false, "item_blocked_on":[ { "start_date":"2017- ...

When working with the Google Sheets API, an error occurred: "this.http.put(...).map is not a valid

Having difficulty with a straightforward request to the Google Sheets API using the PUT method. I followed the syntax for http.put, but an error keeps popping up: this.http.put(...).map is not a function. Here's my code snippet: return this.http ...

Issue: Unable to find suitable routes for navigation. URL Segment: 'profile' or Encounter: Server could not load resource as response status is 401 (Unauthorized)

Currently, I am working on the MEANAUTH application and encountering an issue with accessing user profiles using angular jwt. When attempting to log in and access user profiles at https://localhost:3000/profile, I receive the following error message: Faile ...

The value of Component variable is not defined

I am facing an issue with my User variable being undefined after calling my service. Here is the code snippet : import { User } from './user/user'; import { AppService } from './app.service'; import { Component, OnInit } from '@an ...

Converting an array of floating point numbers into JSON format using JavaScript

After gathering and rounding geocoordinates in PHP, the expected results are as follows: Array( [0] => Array ( [0] => 37.76073 [1] => -122.439948 ) [1] => Array ( [0] => 37 ...

What is preventing me from accessing an object within an array in Redux?

After fetching an array of objects from an API and storing them in the state, I encountered an issue. While I was able to successfully load the entire array into my state and view it in a console log, I faced trouble accessing specific values from the keys ...

Creating a personalized attribute directive within Angular2

I've been attempting to apply a custom attribute directive to an input element, but I'm struggling to achieve it. Here is my directive code: @Directive({ selector: '[disable-paste]' }) export class DisablePaste { constructor(p ...

Utilizing Mongodb to compare distinct elements within a single array

I need to compare two elements in an array. If the code of element[0] is equal to the code of element[1], return true. "SourceArray" : [ { "source" : "Acetone", "code" : "90915 ...