Categories
JavaScript Answers

How to Push JSON Objects into a JSON Array Stored in Local Storage?

Spread the love

Sometimes, we want to push JSON objects into a JSON array in local storage.

In this article, we’ll look at how to push JSON objects into a JSON array in local storage.

Push JSON Objects into a JSON Array in Local Storage

To push JSON objects into an array in local storage, we can push the object into an array, then we can stringify that array and put it into local storage.

For instance, we can write:

const a = [];
const obj = {
  foo: 'bar'
}
a.push(obj);
localStorage.setItem('session', JSON.stringify(a));

to create the a array.

Then we create the obj object that we put into the a array by calling push on a with obj as the argument.

Finally, we store the a array by putting it in an entry with key set to 'session' and a as the corresponding value with:

localStorage.setItem('session', JSON.stringify(a));

We’ve to convert the a array into a JSON string with JSON.stringify before we can store it in local storage with localStorage.setItem .

Conclusion

To push JSON objects into an array in local storage, we can push the object into an array, then we can stringify that array and put it into local storage.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *