Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Store an array in Web Storage using sessionStorage

I’d appreciate any hints, I need to write a code that uses Web Storage in such a way that JSON.parse(sessionStorage.getItem(‘fruits’))[0].name evaluates to ‘Banana’

How I understand this is that first I need to use sessionStorage.setItem to store an array and then the code above will get it. That’s what I managed to do so far (storing an object not an array)
sessionStorage.setItem('fruits', JSON.stringify({ name: 'Banana' }))

I also understand that it’s an array of fruits and I need to get the first element from it, but don’t know how to declare it properly.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to wrap the object in square brackets, so it is in an array.

sessionStorage.setItem('fruits', JSON.stringify([{ name: 'Banana' }]))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading