我有类型的对象:
export interface IGroupLanguage {
name: string;
languages?: Language[];
}
let data = [ { "name": "Automation", "languages": [ { "Name": "English", "Lcid": 1, "RightToLeft": true, "Code": "EN", "Mapped": true } ] }, { "name": "Monitors", "languages": [ { "Name": "Russian", "Lcid": 2, "RightToLeft": true, "Code": "RU", "Mapped": true } ] } ];
然后我尝试过滤对象并返回一个新对象:
this.filteredObject = [...this.groups];
this.filteredObject.map(item => {
item.languages = item.languages.filter(
lg =>
lg.Name.toLocaleLowerCase().indexOf(searchQuery) != -1 ||
lg.Code.toLocaleLowerCase().indexOf(searchQuery) != -1
);
});
问题是初始对象this.groups也发生了变化。如何保存对象的初始语句?
结果我不需要修改 objectthis.groups和过滤 object this.filteredObject。
我知道问题是因为 JS 通过引用复制对象,但我不知道如何解决它。
完整代码为:
search(searchQuery: string) {
this.filteredObject = [...this.groups];
this.filteredObject.map(item => {
let tempLang = [...item.languages];
item.languages = tempLang.filter(
lg =>
lg.Name.toLocaleLowerCase().indexOf(searchQuery) != -1 ||
lg.Code.toLocaleLowerCase().indexOf(searchQuery) != -1
);
});
console.log(this.groups);
}
ngOnInit() {
this.filteredObject = [...this.groups];
}
结果初始对象console.log(this.groups);也被修改
潇湘沐
叮当猫咪
holdtom
相关分类