Win*_*ter 3 javascript arrays object
我正在尝试更新数组中对象的字段。
我的对象(简化)看起来像这样:
{
"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"
}
]
}
Run Code Online (Sandbox Code Playgroud)
我这样称呼它:
prepareRepositories(this.props.primarySearchRepositories);
Run Code Online (Sandbox Code Playgroud)
我可以有几个类似的存储库,然后循环浏览它们。对于数组中的每个项目,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;
}
Run Code Online (Sandbox Code Playgroud)
但是,当我这样做时,原始对象被修改,并且QSString每个存储库的属性都设置为相同的内容。
我究竟做错了什么?
Array.map不会更改原始数组,即创建一个新数组。然而,数组中的任何对象都继续保留相同的引用,因此,即使在映射函数内部对象的任何更改都会更新原始数组中的对象。
您需要为该对象创建一个副本。
item = JSON.parse(JSON.stringify(item))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2637 次 |
| 最近记录: |