kunal
kunal

Reputation: 23

Angular 6:Change array item in localStorage

I want to change Object property in local storage. The object will be like this

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":"[email protected]","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}

Like Just want to change value of "mothername" from array and add new value.

Upvotes: 1

Views: 2803

Answers (2)

Saptarshi Basu
Saptarshi Basu

Reputation: 9283

One line approach using the new spread operator:

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

Upvotes: 0

Torab Shaikh
Torab Shaikh

Reputation: 456

You can't edit the local storage value after it is saved but you can get it back, store it in an object, edit the desired property of object then save it again in the local storage.

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

Don't forget to stringifying it on saving as local storage only save strings and parsing it in object when getting.

Upvotes: 4

Related Questions