Angular 6:更改localStorage中的数组项

时间:2018-10-26 08:58:48

标签: arrays angular6 angular-local-storage

我想更改本地存储中的Object属性。该对象将是这样

appID: {"userid":0,"username":null,"password":null,"saltPassword":null,"kraPassword":null,"kraPasskey":null,"panNumber":"BTRGH8774L","dob":"20/05/1980","address1":"24, New Palasia","address2":"Near vvds","address3":"dvdd","city":"","state":"","pincode":452001,"firstname":"Ramesh","middlename":"","lastname":"Patidar","fathername":"dvdvd","mothername":"vdsddvdsvdsvdsd","maritalStatus":null,"gender":1,"aadharNumber":"741204513909","mobile":"9479897412","email":"dvdsv@bha.com","token":null,"customerId":1,"strDob":null,"ekycApplicationId":1,"stage":"UPLOAD DOCUMENT","dd":null,"mm":null,"yyyy":null,"updatedAt":"26/10/2018","filter":null,"country":null,"stageId":null,"companyName":null,"openLayout":true}

就像只是想从数组中更改“母亲名”的值并添加新值。

2 个答案:

答案 0 :(得分:0)

保存后,您无法编辑本地存储值,但可以将其取回,将其存储在对象中,编辑所需的对象属性,然后再次将其保存在本地存储中。

let item =JSON.parse(localStorage.getItem(key));
item['mothername']='New value';
localStorage.setItem(key, JSON.stringify(item));

别忘了在保存时对其进行字符串化,因为本地存储仅保存字符串并在获取时将其解析为对象。

答案 1 :(得分:0)

使用新的价差运算符的单行方法:

localStorage.setItem('appID', 
    JSON.stringify(
    { ...JSON.parse(localStorage.getItem('appID')), 
      ...{ 'mothername': 'Mommy' }})
);