How to Store an Array in Localstorage

How do I store an array in localStorage?

localStorage only supports strings. Use JSON.stringify() and JSON.parse().

var names = [];
names[0] = prompt("New member name?");
localStorage.setItem("names", JSON.stringify(names));

//...
var storedNames = JSON.parse(localStorage.getItem("names"));

You can also use direct access to set/get item:

localstorage.names = JSON.stringify(names);
var storedNames = JSON.parse(localStorage.names);

How to store an array of objects in Local Storage?

The issues with that code are:

  1. You're wrapping the result you get in an array, but in theory, you want to already have an array.

  2. You're storing user, not get or abc. (You removed that with an edit.)

To store the array, do what you're doing:

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

To get the array:

users = JSON.parse(localStorage.getItem("users") || "[]");

Note how that provides a default (empty array) if getItem returns null because we've never stored our users there.

To add a user to the array:

users.push({id: 1, foo: "bar"});

Example (live on jsFiddle [Stack Snippets don't allow local storage]):

(function() { // Scoping function to avoid creating globals
// Loading
var users = JSON.parse(localStorage.getItem("users") || "[]");
console.log("# of users: " + users.length);
users.forEach(function(user, index) {
console.log("[" + index + "]: " + user.id);
});

// Modifying
var user = {
id: Math.floor(Math.random() * 1000000)
};
users.push(user);
console.log("Added user #" + user.id);

// Saving
localStorage.setItem("users", JSON.stringify(users));
})();

That shows you the list of current users in the console, adding one each time you refresh the page.

How to store an array in localStorage?

Here is a complete example on how to work with an API + use localStorage properly in Nuxt

<template>
<div>
<button @click="cleanPlaylist">Clean the playlist</button>

<p>Items</p>
<ul v-for="user in users" :key="user.id">
<li>
<span>{{ user.name }}</span> ~
<span>{{ user.email }}</span>
<button @click="saveToLocalStorage(user)">Save this user</button>
</li>
</ul>
</div>
</template>

<script>
export default {
data() {
return {
users: [],
}
},
async fetch() {
const response = await fetch('https://jsonplaceholder.typicode.com/users')
const json = await response.json()
console.log('json', json)
this.users = json
},
methods: {
saveToLocalStorage(user) {
if (localStorage.getItem('playlist')?.length) {
const currentUsers = JSON.parse(localStorage.getItem('playlist'))
console.log('current users', currentUsers)
const newData = [...currentUsers, user]
localStorage.setItem('playlist', JSON.stringify(newData))
} else {
localStorage.setItem('playlist', JSON.stringify([user]))
}
},
cleanPlaylist() {
localStorage.removeItem('playlist')
},
},
}
</script>

A codesandbox can be found here.

You should have a good amount of example code + there are some console.log to understand what is happening. Of course, the browser devtools (Application tab) are recommended.

localstorage - save array

It's realy easy, you just need to use JSON data to save it :

// Save
var datas = ["1", "2", "3"];
localStorage["datas"] = JSON.stringify(datas);

// Retrieve
var stored_datas = JSON.parse(localStorage["datas"]);

How to store array in localStorage Object in html5?

localStorage is for key : value pairs, so what you'd probably want to do is JSON.stringify the array and store the string in the mycars key and then you can pull it back out and JSON.parse it. For example,

var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";

localStorage["mycars"] = JSON.stringify(mycars);

var cars = JSON.parse(localStorage["mycars"]);

Unable to store array in local Storage using javascript

For the storage of data in local storage is it very important to remember you can only store string values. When storing objects or array (or arrays of objects) you must convert the data to JSON first.

This is simple:

localStorage.setItem("record", JSON.stringify(data));

And to read the value again:

var record = JSON.parse(localStorage.getItem("record"));

If you do not do this Javascript will try to stringify the data itself using the toString() method. For objects this means the value [object Object] will be stored and not the actual contents of the object.

Also it appears you are confusing Javascript objects and arrays.

This is an object:

{
firstName: "John"
ID: "10"
}

And this is an array:

[10, 20, 30, 40, 50]

Note the use of '{' and '}' when defining an object and the use of '[' and ']' when defining an array. Also note we can have named property in an object which we cannot have in an array.

An array of objects would then look like this:

[
{
firstName: "John"
ID: "10"
},
{
firstName: "Mary"
ID: "20"
}
]

How do you update an array in localStorage without overwriting same-key values?

I've cleaned up the code a little.

Your code should work, except that is was missing some error handling for the first load.

// Mock data
const name = { value: 'Foo name' };
const about = { value: 'Bar about' };
const submitbtn = document.getElementById('submit');

// Fake localStorage to make it work in the snippet
mockLocalStorage = {
getItem: (key) => this[key],
setItem: (key, value) => this[key] = value
};

submitbtn.addEventListener('click', function() {
// Make sure we get -something- back in case this is the first time we're accessing the storage.
const oldInfo = JSON.parse(mockLocalStorage.getItem('data') || '[]');
console.log('Before', oldInfo);

// The creation of the new object can be done in 1 step.
const array = Object.entries({
name: name.value,
about: about.value
});

oldInfo.push(array); // Appends newInfo to oldInfo without overwriting oldInfo data
console.log('After', oldInfo);
mockLocalStorage.setItem('data', JSON.stringify(oldInfo));
});
<button id="submit" type="button">Submit!</button>


Related Topics



Leave a reply



Submit