arrays - 如何在不更新基本数组的情况下更新数组
问题描述
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
。不确定我是否做错了什么。
解决方案
解构对对象进行浅拷贝。这意味着副本和原始对象的内部对象将相同。你需要某种深度克隆。
最简单(不是最好)的方法是对原始内容进行字符串化:
const configCopy = JSON.parse(JSON.stringify(this.config));
推荐阅读
- ember.js - 即使存在于数据存储中,相关对象也不会显示
- python - 根据数据更改 numpy 数组大小
- html - :hover 在使用类来定位 Font-Awesome 图标时不起作用
- python - 在 kivy 应用程序中添加 MDdatatable 后下拉菜单未打开
- python - 对于 Project Euler #5,除了蛮力之外,还有更有效的方法吗?
- python - 不能使用 pandas,TypeError: 'int' object is not subscriptable
- javascript - 如何使方法返回静态属性中“保存”的类型?
- php - 为 PHP 查询创建准备好的语句
- reactjs - 如何在jsx中使用包含冒号的属性名称
- css - 在 CSS 代码中用 ':is()' 替换每个 ':-moz-any()' 伪类有什么问题吗?