Home > Back-end >  access nested object values from local storage
access nested object values from local storage

Time:12-15

how to get nested object values from localstorage. for example,

"metadata": "{"receiver":{"name":"John"},"document":{"type":"Sample doc"},"issuer":{"signatory":"Admin2"}}", "options": "{"title":"Document Title","expireOn":"2022-03-12T00:00:00.000Z"}"

i need to store and get values of "name:john", "type:sample", "signatory:Admin".

answer much apreciated. thank you

localStorage.setItem('metadata', JSON.stringify(data.metadata));
      let metadata = localStorage.getItem('metadata');

      console.log('metadata: ', JSON.parse(metadata));

CodePudding user response:

Have tried to save and get your JSON in localstorage.

Steps for getting nested object value.

Step 1: Sample JSON var data = {"metadata":{"receiver":{"name":"John"},"document":{"type":"Sampledoc"},"issuer":{"signatory":"Admin2"}},"options":{"title":"DocumentTitle","expireOn":"2022-03-12T00: 00: 00.000Z"}};

Step 2: Converting JSON Object to a String format and Save in Localstorage window.localStorage.setItem("metadata", JSON.stringify(data.metadata));

Step 3: Fetch Stringify JSON from localstorage and parse var metadata = JSON.parse(window.localStorage.getItem("metadata"));

Step 4: Fetch nested Object value console.log(metadata.receiver.name)

Hope this answer is useful.

CodePudding user response:

At first you should get the localStorage values and convert that to a JavaScript Object.

let metadata = JSON.parse(localStorage.getItem('metadata'))

Then you can easily get or store data.

// Store 
metadata.receiver.name = 'example'

// Get
let name = metadata.receiver.name
 

You can do this way for other values also.

  • Related