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.

James Z
  • 12,209
  • 10
  • 24
  • 44
Vinz and Tonz
  • 3,487
  • 5
  • 21
  • 32

2 Answers2

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

Roberto Zvjerković
  • 9,657
  • 4
  • 26
  • 47
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)
        };
    });
}
mbojko
  • 13,503
  • 1
  • 16
  • 26