Languages

JavaScript - how to store array of objects in local storage?

0 points
Asked by:
May87
827

How can I store an array of objects inside local storage?

Let's say I have the following array:

const users = [
    { id: 1, name: 'Ann' },
    { id: 2, name: 'Tom' },
    { id: 3, name: 'Kate' }
];
1 answer
0 points
Answered by:
May87
827

The first thing you need to do is use JSON.stringify() method to convert array of objects into string. Then using setItem() method you can save it in the local storage.

// ONLINE-RUNNER:browser;

const users = [
    { id: 101, name: 'Ann' },
    { id: 102, name: 'Tom' },
    { id: 103, name: 'Kate' }
];

localStorage.setItem('users', JSON.stringify(users));

 

See also

  1. JavaScript - store array in localStorage

  2. JavaScript - how to use localStorage?

References

  1. Storage.setItem() - Web APIs | MDN
  2. JSON.stringify() - JavaScript | MDN
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join