How to Store Objects in Html5 Localstorage

How to store objects in HTML5 localStorage

Looking at the Apple, Mozilla and Mozilla again documentation, the functionality seems to be limited to handle only string key/value pairs.

A workaround can be to stringify your object before storing it, and later parse it when you retrieve it:

var testObject = { 'one': 1, 'two': 2, 'three': 3 };

// Put the object into storage
localStorage.setItem('testObject', JSON.stringify(testObject));

// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');

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

How to store object in localStorage

You can only store strings in local storage.

You can encode simple objects as JSON (they must contain only JSON data types such as objects, numbers, and strings) as a string using JSON.stringify(someObject).

var value = JSON.parse(localStorage

… and that is how to convert the JSON back to an object afterwards.


Your code iHandle.find("ul li.pModel.active") implies you are not dealing with a simple object though. That is something I would expect to return a DOM element or something akin to it.

You would need to extract the data you care about from it, store that in an object, store that in the JSON and then the localstorage, and write more code to convert the simple data back in to the full object when you pull the data out afterwards.

Storing Objects in localStorage

local storage limited to handle only string key/value pairs you can do like below using JSON.stringify and while getting value JSON.parse

var testObject ={name:"test", time:"Date 2017-02-03T08:38:04.449Z"};

Put the object into storage:

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

Retrieve the object from storage:

var retrievedObject = localStorage.getItem('testObject');

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

Storing a javascript object in HTML5 local storage

You have to first convert the object into json and then store in local storage. And when you want to reuse the stored data you have to deserialize the json string into javascript object and it will work fine.

Working Sample

function setValue() {
var obj = new user();
var jsonObject = JSON.stringify(obj);
sessionStorage.setItem("Gupta", jsonObject);
getValue();
}

function user() {
this.Name = "rahul";
this.Age = 20;
}

function getValue() {
var json_string = sessionStorage.getItem("Gupta");
var obj = JSON.parse(json_string)
alert("Name = "+obj.Name + ", Age = " + obj.Age);
}

How to assign an object to local storage instated of assigning with every single item?

You have to use JSON.stringify(data); in order to store object in local storage.

Make sure you create your complete object in JavaScript itself (as per your requirement). And then once your object is ready, use JSON.stringify method to save objects in your local storage.

And to retreive back the data you will use JSON.parse() to get back the Object and then you can use any JavaScript methods to perform your tasks as per the requirement.

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"]);

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 every items in localstorage in javascript?

localStorage.setItem will add that key to the localstorage of the browser, or oerwites that key's value if it already exists.

So your old data will be overwritten once you executes localStorage.setItem

What you have to do is, you have to extract the current value in local storage using localStorage.getItem, add the new value to that extracted value and update the local storage with the new value that consist of old and new data.

So your code will be something like below

function addToCartClicked(event) {
var Title, Price, Image
var button = event.target
var shopItem = button.parentElement.parentElement.parentElement.parentElement
var title = shopItem.getElementsByClassName("name-of-product")[0].innerText
var price = shopItem.getElementsByClassName('product-price')[0].innerText
var image = shopItem.getElementsByClassName("hover-img")[0].src

let itemsList = {
Title: title,
Price: price,
Image: image,
}
let cartItems = localStorage.getItem("productsInCart");
cartItems = cartItems ? JSON.parse(cartItems) : {};
cartItems[itemsList.Title] = itemsList;
localStorage.setItem("productsInCart", JSON.stringify(cartItems));
cartItems = localStorage.getItem("productsInCart");
cartItems = JSON.parse(cartItems);
console.log("This is without json", cartItems);
}


Related Topics



Leave a reply



Submit