Store object from local storage into variable - javascript

I am trying to retrieve a object from localstorage and trying to load it into a variable . How can i do this ? This is where i m stuck
var messageStorage={};
messageStorage.retrieve = function () {
var storageString = localStorage.getItem(credentials.mobileNumber);
var storageObj = JSON.parse(storageString);
// whats should go here for messageStorage to be equal to storageObj
};
On messageStorage.retrieve(); the variable messageStorage must contain the value from localstorage.

with localStorage the data is actually stored as a string.
And you use JSON.parse to return the value
JSON.parse() Returns the Object corresponding to the given JSON text.
Example :
JSON.parse('{}'); // {}
JSON.parse('true'); // true
JSON.parse('"foo"'); // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse('null'); // null
But i saw that you want to return the variable. So what's the type of this variable ? Number, String, Boolean ? You can convert from String to what you need

localStorage allows you to save only strings, so if you have to save an object you should save it as a JSON string or you can use this library to solve your issue

first of all we can't store objects to localstorage, only strings are allowed:
localStorage.setItem("test", JSON.stringify(jsondata));
var item = JSON.parse(localStorage.getItem("test"));
now you have json data to parse it and get the value.

Related

Can you save something in LocalStorage with a variable?

So this is a quick question, but I was unable to find an answer anywhere.
I know to save things in localStorage you write like this:
localStorage.name = JSON.stringify("this has now been saved under name);
But I want to be able to change what it is saved under depening on a variable, like this:
const banana = potato
localStorage.banana = JSON.stringify("this has now been saved under potato");
Is this possible to do? :)
​​​​​​​
Localstorage allows for the storage of key and value pairs where the value is a string.
If you are assigning to localstorage from reference to another variable, if it resolves to a string then that will work:
const potato = "potato";
const banana = potato;
localStorage.setItem(banana, "this has now been saved under potato");
Otherwise you will need to stringify the value of the variable first.
https://www.w3schools.com/html/html5_webstorage.asp
You can set variables in localStorage with dynamic keys like
const banana = potato
localStorage.setItem(banana, "this has now been saved under potato")
You can add data to your localstorage. You have an key and a value,both need to be strings.
window.localStorage.setItem('myCat', 'Tom');
and you can get it like this:
window.localStorage.getItem("myCat");
To store an variable, array, object etc. you will need to convert it to an string first like this for example:
let arr = [1, 2, 3];
//you need to convert this array to an string.
let arr_string = JSON.stringify(arr);
//now you can store it in your local storage
window.localStorage.setItem("myArray", arr_string);
//to get the array you will need to parse it back from string to array.
let arr_string = window.localStorage.getItem("myArray");
let arr = JSON.parse(arr_string);
console.log(arr); // output: [1, 2, 3]

Using localStorage/sessionStorage to store arrays

I am trying to save an array inside of a localStorage value. I can only access chars of the value, not the grouped value. I have been trying to write a function to group them by commas, but I can't figure out how to do it correctly.
// setting values
localStorage.setItem("foo", [15,"bye"]);
// writes the whole thing.
document.write(localStorage.getItem("foo")); // returns 15,bye
// only writes the first character, instead of one part of the array
// (in this case it would be 15).
document.write(localStorage.getItem("foo")[0]); // returns 1
I would use JSON.stringify to set the data and JSON.parse to fetch the stored data.
Try this:
localStorage.setItem("foo", JSON.stringify([15,"bye"]));
// writes the whole thing.
localStorage.getItem("foo"); // returns 15,bye
var data = JSON.parse(localStorage.getItem("foo"));
console.log(data[0])
localStorage can only store string in its value, that is why it is storing only 15;
Use JSON.stringify and store it in the local storage as localStorage.setItem("foo",JSON.stringify([15,"bye"]));
If you want to retrieve the value do as JSON.parse(localStorage.getItem("foo"));
You can parse json
let data = JSON.parse(localStorage.getItem("foo"));
console.log(data[0])
Or you can split by ',' and get the 0th index item.
localStorage.getItem('foo').split(',')[0]

Can a localStorage value be an object or array?

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.

how to make a string which showed like an array return to array when add to an object in Javascript

i got a string which was actually an array as I got it from database.
0
when i add it to an object, it becomes a string with quotation mark "" , but i want it to be array, what should I do?
e.g.
temp = [{"abc"=123},{"bcd"="234},...] //this is actually a string
helloObj = {items:temp};
consol.log(helloObj); //will become items: "[{"abc"=123},{"bcd"="234},...]"
//I want it become items: [{"abc"=123},{"bcd"="234},...]
//I have tried below, not work:
temp = [temp];
helloObj = {items:temp};
consol.log(helloObj); //will become items: ["[{"abc"=123},{"bcd"="234},...]"
]
What you have is a JSON string. You need to parse it from the JSON notation which will convert it to an object (array in this case).
var aray = JSON.parse('[{"abc"=123},{"bcd"="234},...]');
console.log(aray);
So you're getting JSON back from your database. Simply run JSON.parse(str) where str is your string and it will convert it back to an array.

Converting JSON to Usable object in Javascript

I have some JSON with two parameters expressed as
{"pushid":"35336165333161382d646338302d346665302d626236312d303763313435663036656131","count":1}
I'm trying to get access to the "pushid" and the "count" as usable elements, either in an object, an array or a map, and am a little confused as to how to do that.
When I call JSON.parse(json) it returns undefined, and so I assume that it's already an object. However, when I try to use json[1] it returns the second character of the whole thing (which in this case is "). How do I make an object
var obj = {pushId: SOME_STRING, count: SOME_INT)?
Thanks in advance,
Considering:
var jsonString = '{"pushid":"35336165333161382d646338302d346665302d626236312d303763313435663036656131","count":1}';
You can do:
var jsonObj = JSON.parse(jsonString);
console.log(jsonObj.pushid); // 3533...
console.log(jsonObj['pushid']); // 3533...
console.log(jsonObj.count); // 1
console.log(jsonObj['count']); // 1
console.log(jsonObj[0]); // undefined
console.log(jsonObj[1]); // undefined
This is already an object so you don't have to parse it. {"pushid":"35336165333161382d646338302d346665302d626236312d303763313435663036656131","count":1}
All you have to do is now assign it to what ever variable you want.
let data = {"pushid":"35336165333161382d646338302d346665302d626236312d303763313435663036656131","count":1};
console.log("pushid : " + data["pushid"]);
pushid : 35336165333161382d646338302d346665302d626236312d303763313435663036656131
console.log("count : " + data["count"]);
count : 1
I mean, that number is too long for JS to represent in it's 64 bit floating point internal representation, but you can try to parse the base16 repr with
parseInt(obj.pushid, 16);

Categories

Resources