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:
You're wrapping the result you get in an array, but in theory, you want to already have an array.
You're storing(You removed that with an edit.)user
, notget
orabc
.
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
Download File Using an Ajax Request
Using Html5/Canvas/JavaScript to Take In-Browser Screenshots
Maximum Call Stack Size Exceeded Error
How to Change an Element'S Text Without Changing Its Child Elements
Dynamically Set Value of a File Input
Difference Between Val() and Text()
How to Impose Maxlength on Textarea in HTML Using JavaScript
How to Scroll to an Element Using JavaScript
(Change) VS (Ngmodelchange) in Angular
How to Create a New Line in JavaScript
How to Save an Html5 Canvas as an Image on a Server
JavaScript Code to Stop Form Submission
Jquery Id Selector Works Only For the First Element
Is There a Spec That the Id of Elements Should Be Made Global Variable
Contenteditable, Set Caret At the End of the Text (Cross-Browser)
Browser/Html Force Download of Image from Src="Data:Image/Jpeg;Base64..."