Saving and getting an array in Localstorage? - javascript

I am trying to save an array into localstorage and then get it.
localStorage.setItem("savedquestionslist", questions);
console.log(localStorage.getItem(savedquestionslist));
The variable 'questions' is an array.
However I get this error:
ReferenceError: savedquestionslist is not defined.
I still get the error even if I do this:
localStorage.setItem("savedquestionslist", "test");
console.log(localStorage.getItem(savedquestionslist));
Does anyone know what the issue is? Thanks

savedquestionslist needs to be a string.
console.log(localStorage.getItem('savedquestionslist'));

The problem is in your syntax for getItem.
It takes in a string as an argument. You are passing a variable and the error represents that the variable savedquestionslist is not defined.
Change your code to :
localStorage.setItem("savedquestionslist", questions);
console.log(localStorage.getItem("savedquestionslist"));
An example would be
var questions = ['firstQuestion', 'secondQuestion', 'thirdQuestion'];
localStorage.setItem("savedquestionslist", questions);
console.log(localStorage.getItem("savedquestionslist"));

The error you're getting is because you forgot the quotes in the getItem call:
console.log(localStorage.getItem("savedquestionslist"));
// ------------------------------^------------------^
Or you can use literal access:
console.log(localStorage.savedquestionslist);
But in both cases, since local storage only stores strings, I'd use JSON, since otherwise your array won't be saved / retrieved correctly:
localStorage.setItem("savedquestionslist", JSON.stringify(questions));
console.log(JSON.parse(localStorage.getItem("savedquestionslist")) || []);
(The || [] is for if you've never set the item, it provides a default of an empty array.)

Related

Array is null when trying to use .push after localstorage

I get a TypeError saying my array is null when I try to push a new value into it.
//first off..
var sillyArray= ["dummy"];
localStorage.setItem("sillyArray", JSON.stringify(sillyArray));
//I later used this
sillyArray = JSON.parse(localStorage.getItem("sillyArray"));
//the error is here
sillyArray.push("yes");
localStorage.setItem("sillyArray", JSON.stringify(sillyArray));
Am I unable to push or parse this?
(Edited a posting error)
The yesArray was never definded. That's why it's impossible to .push().
Yes, you can but you are trying to push an item into a undefined var, this is why you get a TypeError.
Here is how you should do that:
var array = ['dummy'];
localStorage.setItem('someKey', JSON.stringify(array));
array = JSON.parse(localStorage.getItem('someKey'));
array.push('foo');
localStorage.setItem('someKey', JSON.stringify(array));
then if you do
console.log(JSON.parse(localStorage.getItem('someKey')))
the output will be what you are expecting ["dummy", "foo"]
As user nnnnnn said, I hadn't properly executed mylocalStorage.setItem("sillyArray", JSON.stringify(sillyArray));
It was sitting in an if statement (not pictured) that wasn't executing causing the null.
Thanks guys!

JSON Parsing in AngularJS Service

I have Angular service and in that service I have a code:
this.testMethod = function( ) {
this.jsonTest = "[{'id':'123','title':'XYZ','id2':'456','status':2}]";
this.parseTest(this.jsonTest);
};
this.parseTest = function(jsonTest) {
var jsonTestObj = JSON.parse(jsonTest); // I get error hear
}
Test method is getting called on ng-click event.
Error that I am getting while testing in latest chrome browser:
SyntaxError: Unexpected token ' at Object.parse (native)
......
I tried multiple things to fix it but nothing seems to work.
Every time I get undefined value error.
Basically I want to parse JSON object and get the values.
What am I doing wrong?
Use this
this.jsonTest = '[{"id":"123","title":"XYZ","id2":"456","status": "2"}]';
Or this
this.jsonTest = "[{\"id\":\"123\",\"title\":\"XYZ\",\"id2\":\"456\",\"status\": \"2\"}]";
You either need to use ' outside or " outside and escape the quotes inside.
Both the key and value need to be in double quotes.
You need to use double quotes in your string, other than that your code should work.
To quote from specification
A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.
Your JSON is not valid. Always check your JSON integrity in those cases, i personaly use
http://jsonlint.com/

How to get the value mapping of a Chrome local storage result through an argument?

I have a function:
// Get the value out of Chrome local storage
chrome.storage.local.get(sourcePath, function(result) {
// Test the result
alert(JSON.stringify(result.sourcePath));
});
And a call to check it:
chrome.storage.local.set({'userAcceptanceAgreement': true});
Right now, I would like to know how to get my function, when called with the above argument, to pass that value into the result.sourcePath alert. As is, it shows result with the correct storage value of {'userAcceptanceAgreement': true}, but result.sourcePath comes up as undefined because it isn't trying to locate the key:value pair for the argument, but for a literal sourcePath.
Basic JavaScript here.
var sourcePath = 'userAcceptanceAgreement';
result.sourcePath; // Accesses literally "sourcePath"
result[sourcePath]; // Accesses "userAcceptanceAgreement"
Note that you buried the problem under a lot of noise. Please consider constructing a minimal example next time.

Unable to fetch object value

I am struggling to figure out why I am getting "undefined" when trying to fetch a certain object value.
My object, called "message" looks like this:
{"username":"123","password":"123"}
When I try to fetch either username or password with the following:
message.username
message['username']
I get "undefined".
What's the correct way to fetch the values?
Code that gets the message and displays it:
window.messageBus.onMessage = function(event) {
displayText(event.data); // spits out {"username":"123","password":"123"}
}
function displayText(message) {
document.getElementById("message").innerHTML = message.username + ' - ' + message.password;
};
EDIT - The object is being received by Chromecasts "window.messageBus.onMessage" function. I assumed because I sent the message as a proper object, it should have bene spat back as a proper object, but it seems that might not be the case!
Well, no idea why it wasn't working with the code I posted, as by all means it should have.
Anyway, I fixed it by using "JSON.parse()" on the "message" variable passed to "displayText()"
I was then able to use "message.username" to get the value.
No point defining your variables in "", see the following example:
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
alert(person.firstName);
That is the right way of defining and accessing the objects in Javascript

How to handle empty or null expressions while assigning as JS variable?

I am using EL expressions in my javascript code as shown below:
cur_step = #{obj1.step};
This works fine when there actually is a value inside obj1.step. However, if there is no value or is null, this is how the javascript is rendered in the browser:
cur_step = ;
This results in javascript error preventing my javascript from executing at all.
How do I fix this problem?
The obj1 object is a java bean populated on the server. FYI, I use JSF2.1 with jboss-el-2.0.jar as my EL implementation.
You could do a null check in your expression:
#{empty obj1.step ? 'something else' : obj1.step}
The empty keyword covers null and empty strings.
You could use a temporary array:
cur_step = [#{obj1.step}][0];

Categories