我正在尝试更新数组中对象的字段。
我的对象(简化)看起来像这样:
{
"readableStructure": [
{
"ID": "1",
"Name": "Name 1",
"Description": "Adding, updating or removing users",
"IconName": "fas fa-users-cog"
},
{
"ID": "2",
"Name": "Name 2",
"Description": "Views overview",
"IconName": "fas fa-street-view"
},
{
"ID": "3",
"Name": "Name 3",
"Description": "Improvements to apps",
"IconName": "fas fa-broadcast-tower"
},
{
"ID": "4",
"Name": "Name 4",
"Description": "Managing badges",
"IconName": "fas fa-id-badge"
},
{
"ID": "5",
"Name": "Name 5",
"Description": "Art",
"IconName": "fas fa-hand-holding-heart"
}
]
}
我这样调用它:
prepareRepositories(this.props.primarySearchRepositories);
我可以有几个类似的存储库,然后循环浏览它们。对于数组中的每一项,我尝试使用以下代码添加一个名为 QSString
的属性。
prepareRepositories(repositories) {
const repos = repositories.map((repo, index) => {
const searchableColumns = ['Name', 'Description'];
const newRepo = [];
newRepo[0] = {};
newRepo[0].readableStructure = [];
newRepo[0].readableStructure = repo[0].readableStructure.map((item) => {
item.QSString = this.getSearchableString(item, searchableColumns) || 'blaha';
return item;
});
return newRepo;
});
return repos;
}
getSearchableString = (base, searchableColumns) => {
let searchables = [];
Object.keys(base).forEach((key) => {
if ((searchableColumns.indexOf(key) > -1) && (base[key] !== null) && (typeof base[key] !== 'object')) {
searchables.push(base[key]);
}
});
const searchableString = searchables.join(' ');
return searchableString;
}
但是,当我执行此操作时,原始对象会被修改,并且每个存储库的 QSString
属性都会设置为相同的内容。
我做错了什么?
最佳答案
Array.map不更改原始数组,即创建一个新数组。但是,数组中的任何对象都会继续保留相同的引用,因此,即使在映射函数内部,对象的任何更改都会更新原始数组中的对象。
您需要为该对象创建一个副本。
item = JSON.parse(JSON.stringify(item))
关于javascript - array.map 正在改变我的原始数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50696633/