首页 > 解决方案 > 如何在不更新基本数组的情况下更新数组

问题描述

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

我在服务类中有这个函数,我从我的角度组件中调用这个方法。

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

我正在创建this.config对象的副本并将其传递给mapconfig函数,以便它不会更新基础对象(this.config),但它总是更新基础对象this.config。不确定我是否做错了什么。

标签: arraysangulartypescriptshallow-copy

解决方案


解构对对象进行浅拷贝。这意味着副本和原始对象的内部对象将相同。你需要某种深度克隆。

最简单(不是最好)的方法是对原始内容进行字符串化:

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

如何在 JavaScript 中进行深度克隆


推荐阅读