[英]array.map is mutating my original array
我正在嘗試更新數組中對象的字段。
我的對象(簡化)看起來像這樣:
{
"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);
我可以有幾個類似的存儲庫,並遍歷它們。 而對於在陣列中的每個項目readableStructure
我想添加一個名為屬性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不會更改原始數組,即創建一個新的Array。 但是,數組中的任何對象繼續保持相同的引用 ,因此,即使在map函數內部,對象中的任何更改都將更新原始數組中的對象。
您需要為該對象創建一個副本 。
item = JSON.parse(JSON.stringify(item))
使用這個不會改變原始對象
JSON.parse(JSON.stringify(your_object))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.