Reputation: 3587
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.
Upvotes: 0
Views: 65
Reputation: 14689
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)
};
});
}
Upvotes: 1
Reputation: 10157
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
Upvotes: 1