0
  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 };
    });
  }

I have this function in a service class , and i am calling this method from my angular component.

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

I am creating a copy of the this.config object and passing it to the mapconfig function so that it will not update the base object (this.config), but its always updating the base object this.config.Not sure if i am doing something wrong.

2 Answers 2

1

Destructuring does a shallow copy of objects. That means the inner objects will be the same for the copy and the original. You need some kind of deep cloning.

The easiest (not the best) way is to stringify the original:

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

How to Deep clone in javascript

Sign up to request clarification or add additional context in comments.

Comments

1

It should be doable without a single mutation, more or less like this:

mapConfig(config: IConfigItem[], dataModel: IDataModel): IConfigItem[] {
    return config.map(c => {
        const entries: [string, string][] = Object.entries(c);
        const entriesToBeReplaced = entries.filter(([val, key]) => key in dataModel);

        const entriesWithReplacedValues = entriesToBeReplaced.map(([val, key]) => ({
            [val]: dataModel[key]
        }));

        return {
            ...c,
            Object.fromEntries(entriesWithReplacedValues)
        };
    });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.