我想要做的是更新数组中的单个值,这是我目前所拥有的代码,但它似乎不能正常工作,我想知道是否有人可以帮助我。
所以,我认为它的工作原理是,它从ngFor中获取索引位置,以及数组的自动递增id,以确保它有匹配,并将新名称推送到数组中。
但这似乎不起作用,它执行toastr来说明它已经更新,但没有在本地存储中
public updateNameLocalStorage(Name, id, i ): void {
const currentArray = this.storage.get(this.STORAGE_KEY);
console.log(currentArray);
for (i = 0; i < currentArray.length; ++i) {
if (currentArray[i].id === id) {
currentArray.push({
Name: Name
});
// insert updated array to local storage
this.storage.set(this.STORAGE_KEY, currentArray);
this.notifiy.showInfo('Name Updated' , '');
} else {
this.notifiy.showFailure('Error' , '');
}
}
这是数据的结构

发布于 2019-08-20 17:36:07
您正在使用push,它将一个元素附加到数组的末尾。如果想用给定的ID更新值,只需直接访问索引并覆盖该值即可。另外,如果您只是按下{Name: Name},数组中的对象将不再具有id属性。
如下所示:
const currentArray = this.storage.get(this.STORAGE_KEY);
const index = currentArray.findIndex(e => e.id === id);
if(index >= 0) {
currentArray[index] = {...currentArray[index], ...{Name:Name}};
this.storage.set(this.STORAGE_KEY, currentArray);
this.notifiy.showInfo('Name Updated' , '');
} else {
this.notifiy.showFailure('Error' , '');
}https://stackoverflow.com/questions/57570247
复制相似问题