I want to access the values from some keys in my Local Storage in the most easiest way with AngularJs.
In Resources --> Local Storage I have:
Key:myKey
Value:{ "layouts":[ other_things ],"states":{ other_things },"storageHash":"fs4df4d51"}
I tried:
console.log($window.localStorage.key(0).valueOf('layouts'));
//or
console.log($window.localStorage.getItem('myKey'));
RESULT
myKey
You can do:
$window.localStorage['myKey']
If the data is of stringified(read: JSON.stringify) then:
angular.fromJson($window.localStorage['myKey']);
LocalStorage stores values in strings, not objects. You will need to serialize your object before assigning it and deserialize it when fetching.
var myObject= { "layouts":[ other_things ],"states":{ other_things },"storageHash":"fs4df4d51"};
// Stringify JSON object before storing
localStorage.setItem('myKey', JSON.stringify(myObject));
// Retrieve the object
var myRetrievedObject = JSON.parse(localStorage.getItem('testObject'));
From local storage you get JSON data, so you need to parse it to JS object,
JSON.parse($window.localStorage.myKey).layouts
Related
How to get nested object values from localstorage.
For example:
"metadata":"{
"receiver":{"name":"John"},
"document":{"type":"Sample doc"},
"issuer":{"signatory":"Admin2"}}",
"options": "{"title\":"Document Title","expireOn":"2022-03-12T00:00:00.000Z"}"
I need to store and get values of name:john, type:sample, signatory:Admin.
localStorage.setItem('metadata', JSON.stringify(data.metadata));
let metadata = localStorage.getItem('metadata');
console.log('metadata: ', JSON.parse(metadata));
Thank you.
At first you should get the localStorage values and convert that to a JavaScript Object.
let metadata = JSON.parse(localStorage.getItem('metadata'))
Then you can easily get or store data.
// Store
metadata.receiver.name = 'example'
// Get
let name = metadata.receiver.name
You can do this way for other values also.
Have tried to save and get your JSON in localstorage.
Steps for getting nested object value.
Step 1: Sample JSON
var data = {"metadata":{"receiver":{"name":"John"},"document":{"type":"Sampledoc"},"issuer":{"signatory":"Admin2"}},"options":{"title":"DocumentTitle","expireOn":"2022-03-12T00:00: 00.000Z"}};
Step 2: Converting JSON Object to a String format and Save in
Localstorage window.localStorage.setItem("metadata", JSON.stringify(data.metadata));
Step 3: Fetch Stringify JSON from localstorage and parse var metadata = JSON.parse(window.localStorage.getItem("metadata"));
Step 4: Fetch nested Object value console.log(metadata.receiver.name)
Hope this answer is useful.
I am trying to create a book tracker app that uses localStorage. However, when I set an item - what happens is that no error message is given but it doesn't log to localStorage. Here is my code:
//var currentId = parseInt(localStorage.getItem("currid"))+1;
var nameOfItem = "bookPackage"+id;
localStorage.setItem(nameOfItem, readBooks);
Assume that currid is already preset in localStorage as a number.
When I go to the console and type in localStorage, here is the result:
StorageĀ {length: 0}
Why is it not working???
Edit: readBooks is an object.
You can only store strings into local storage, if you want to store an object you need to JSON.stringify(obj) first.
var str = "22";
localStorage.setItem('key', str);
var getStr = localStorage.getItem('key');
console.log(parseInt(getStr));
let obj = {a: 'a1', b: 'a2'};
localStorage.setItem('key2', JSON.stringify(obj));
let getObject = localStorage.getItem('key2');
console.log(JSON.parse(getObject));
As #sonEtLumiere has already mentioned, you can only store strings into local/session storage, so if you have objects/arrays, you will have to stringify them with JSON prior to storing them into local/session storage. I'm not sure what "readBooks" is, but since it's plural, I'm assuming it's an array. Because of this, you'll need to use JSON.stringify(data) to store that information.
When you need to retrieve object/array data from local/session storage, you'll have to parse out the data using JSON.
JSON.parse(data)
Just remember, Stringify IN to storage, Parse OUT of storage.
This question already has answers here:
Storing array in localStorage with JSON in javascript
(2 answers)
Closed 3 years ago.
store data and retrieve multidimensional array in local storage java-script
Here I need to store array in local storage. and How do I retrieve?
As only strings can be assigned to localStorage, you have to convert the array to a string before assigning.
Convert the array into a JSON string using JSON.stringify() and using localStorage.setItem() store it in localStorage.
var num = [
['inp1','inp2'],
['inp3','inp4']
];
localStorage.setItem('arr',JSON.stringify(num));
With localStorage we are limited to store data as strings, therefore:
Use JSON.stringify to serialize the data to a string, before storing it in the local storage
const input = [[1], [2], [3]];
localStorage.setItem('myData', JSON.stringify(input));
Use JSON.parse to deserialize the data back to array when reading it form the local storage
const arr = JSON.parse(localStorage.getItem('myData'));
You may try like this:
var multidimensionarray = [
['1','2'],
['3','4']
];
localStorage.setItem('__array', JSON.stringify(multidimensionarray));
console.log(localStorage.getItem('__array'));
You can use JSON.stringify() and JSON.parse() combined with Window.localStorage methods setItem() and getItem():
To store:
localStorage.setItem('myItem', JSON.stringify(myMultidimensionalArray))
And to get the stored data with key myItem:
const array = JSON.parse(localStorage.getItem('myItem'))
Local storage is very simple data storage. It stores key (string) of which value is also (string and only string!). You need to use JSON.stringify(...) to store data and then parse it back JSON.parse(...)
I am trying to set storage in the user's computer with localStorage("save","{teams:5, points:20}, etc. But I'm not sure if the value can be an object. I've checked the internet, but I can't seem to find clear answers there.
var data={
teams:5, points:25,team1:5,team2:10, team3:5, team4:0, team5:5};
localStorage ("save", data);
Thoughts?
No, the key and value must be a DOMString. See https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem
What you can do is serialise your data as JSON before setting it
localStorage.setItem('save', JSON.stringify(data))
When reading the value, you can parse it back into an object
let saveData = JSON.parse(localStorage.getItem('save'))
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));
No, localstorage takes string as and saves it. If you want to save any object then convert it on string and then save it.
while fetching it from local storage you we get string. you may easily covert it into object.
if you directly save an object into localStorage then it will be saved in such manner "[object Object]" and while fetching it from localStorage, you will get "[object Object]" as String.
Wrong Code:
var data={teams:5, points:25,team1:5,team2:10, team3:5, team4:0, team5:5};
localStorage.setItem("save", data);
localStorage.getItem("save")
you will get "[object Object]"
Right Code:
var data={teams:5, points:25,team1:5,team2:10, team3:5, team4:0, team5:5};
localStorage.setItem("save",JSON.stringify(data));
localStorage.getItem("save")
While fetching value from localStorage
Wrong Code:
localStorage.getItem("save")
It will fetch data in form of string.
Right Code:
JSON.parse(localStorage.getItem("save"))
It will return data in form of object.
I hope the solution is well explained.
No, It can't be but you can use stringify. For example:
localStorage.setItem('user', JSON.stringify(r.user));
You need to use the localStorage.setItem(keyName, keyValue);
For Storing a Object, you can make use of JSON.stringify(object) which converts the object to a string.
From MDN
keyName
A DOMString containing the name of the key you want to
create/update.
keyValue
A DOMString containing the value you want to
give the key you are creating/updating.
I have this on link in json format, I have to retrive it
{"vehicles":[{"name":"motorcycle","wheels":2,"maxCapacity":2,"currentPassengers":1,"maxSpeed":"260 km/h"},{"name":"car","wheels":4,"maxCapacity":4,"currentPassengers":3,"maxSpeed":"220 km/h"},{"name":"aeroplane","wheels":18,"maxCapacity":416,"currentPassengers":215,"maxSpeed":"920 km/h"}]}
to store it into a regular javascript object.
var obj = JSON.parse({"vehicles":[{"name":"motorcycle","wheels":2,"maxCapacity":2,"currentPassengers":1,"maxSpeed":"260 km/h"},{"name":"car","wheels":4,"maxCapacity":4,"currentPassengers":3,"maxSpeed":"220 km/h"},{"name":"aeroplane","wheels":18,"maxCapacity":416,"currentPassengers":215,"maxSpeed":"920 km/h"}]})
then you can use as obj.vehicles in order to access vehicles.