Check if certain value exist in localStorage - javascript

I am trying to display a div conditionaly based on if a value exists in localStorage:
So here is an example the values present in localstorage for the key "elementor":
Key = elementor
Value = {__expiration: {}, pageViews: 2, popup_times: 1, popup_disable: true}
How to write a conditional to check if popup_disable: true is present or not?
Thanks!

Just like you would with any other object.
local_storage_value = localStorage.getItem(key)
if (local_storage_value.popup_disable) {
...
}
This checks if popup_disable is set to true, but doesn't check if the key exists in your localstorage.
if("popup_disable" in local_storage_value){
...
}
This checks if the key is present.

Thanks for making me look stupid #alex067 and #epascarello... but most your questions/answers did not make sense!
Obviously am not expert on this thus am here but I figured it out and super simple. So just had to JSON.parse the key and then look for if the popup_disable is in the value like this:
var popupDisable = JSON.parse(localStorage.getItem('elementor'));
if(popupDisable.hasOwnProperty('popup_disable')){
alert('yes');
} else {
alert('no');
}

Related

Reading a sessionStorage property and creating an if statement

So, I want to read a value from sessionStorage. I know how to do this, but then I want to do something like this:
function whiteSet() {
if (// condition: what the heck would I put here?) {
const color = localStorage.getItem('theme');
//if the value 'theme' is equal to 'aluminum' then:
document.getElementById("headerbar").style.backgroundImage = "url(images/themes/aluminum.png)";
} else {
document.getElementById("headerbar").style.backgroundImage = "url(images/themes/galaxy.png)";
};
I don't really know what to do :/
If an answer already exists for this question, I have already tried finding it and failed.
Just take it step by step. First you're reading the value out of local storage and putting it in the variable 'color', then you need to decide what to do based on what value you read out. So instead of starting out with an if statement, get color first and then the conditional tests against its content:
function whiteSet() {
const theme = localStorage.getItem('theme');
if (theme === "aluminum") {
document.getElementById("headerbar").style.backgroundImage = "url(images/themes/aluminum.png)";
} else {
document.getElementById("headerbar").style.backgroundImage = "url(images/themes/galaxy.png)";
};
}
(Personally, since you're storing it in a localStorage key named "theme", I'd name the variable "theme" too instead of "color" just to avoid confusion; but that's more of a coding style thing than a requirement for it to work.)

How to Check the variable value is [""] in JavaScript

Example:
When I check a variable containing this value [""] it returns false.
var th=[]
th.push("");
if($("#multiselect").val()==th)
It returns always false.
Thank you.
Edit 1:
changed Var to var. It was a typo.
Edit 2:
Actually, the problem I faced was I was trying to get the value from a multi-select input. The multi-select input sometimes returns values as [""] even I haven't selected any values basically it's a plugin. So I was confused and I thought [""] is a fixed primitive value like 1, 10, "bla blah",.. So I tried to compare it with the same array as the right-hand side of the '=' operator.
It was stupid. Now I posted the solution to my problem and I explained my stupidity.
there are two things:
Change Var to var
You can use includes method of Array as:
var th = [] <==== chnage Var to var
th.push("");
if(th.includes($("#multiselect").val())) { <=== you can use includes method of array
// DO whatever you want
}
Make sure var is lowercased.
You are accessing th as an array, so you’ll need to specify the index of the value you are checking: th[0]
Use triple equals, too: .val()===th[0]
Double check the jquery docs if you’re still running into trouble.
Happy coding!
A couple of things to consider:
You have a typo in the code above; var is valid; Var is invalid.
Browser will aptly complain to solve this typo.
You are comparing an array to DOM value; this will always be false.
DOM is a costly process. Unless the value associated is dynamic, its better to read once, store value into a variable and continue processing instead of reading from DOM always.
You could choose to try something on these lines:
let arr = [1,2,3,4];
let domValue = $("#multiselect").val();
arr.push(5);
arr.map((el, ix) => {
if el === domValue return true; //or choose to do something else here.
});
var th=[]; //It is var not Var
th.push("");
if($("#multiselect").val()==th[0]) // change th to th[0]
I am unable to comment so having to use an answer for now. Are you trying to check if an array has any values? If so you can use
if(th.length){
// do something
}
If you want to check a normal variable for empty string you can simply use
if(th == “”){
//do something
}
I found the solution after a couple of days when I posted this question. Now I can feel how stupid this question was.
Anyway, I'm answering this question so it might help others.
Answer to my question:
When two non-primitive datatype objects(which is the Array here) are compared using an assignment operator, it compares its reference of the object. So the object creation of both arrays would be different. If I want to check the array has [""] value, I should do something like the below.
function isArrValEmptyCheck(value) {
return !value || !(value instanceof Array) || value.length == 0 || value.length == 1 && value[0] == '';
}
console.log(isArrValEmptyCheck([""]));//returns true
console.log(isArrValEmptyCheck(["value1"]));//returns false
Sorry for the late response. Thanks to everyone who tried to help me.

How to select first of several items in JSON that exists?

JSON files are compromised of a series of key's and values. I know the potential key's in a given JSON, but not whether or not they have corresponding non-empty values. I have loaded the JSON file into an object called JSON. I want to find the first of several possible key's with a value and then assign that value to a variable. When I say "first" I mean "first" according to a priority list that is not related to the structure of the JSON:
I could do the following and it works:
if(json.age)
myValue = json.age;
else if(json.classYear)
myValue = json.classYear;
else if(json.seniority)
myValue = json.seniority
else
myValue = false;
This works but sucks for several reasons:
It is slow to write
It is annoying to rewrite the key value name each twice in each row
It is a little hard to read
It is very difficult to reason with programatically. I don't have a use case that requires this, but I can imagine wanting to arbitrarily change the order of priority from within my code.
While not terribly slow to process, I can imagine that some other approach may compute faster.
These reasons lead me to believe that the method listed above is not ideal. Is there some other pattern that would be better?
(Note: I recognize that this question borders on a "how best to" as opposed to "how to" phrasing. I know SO is not wild about that sort of question and I don't mean my question to be interpreted as such. Rather, my question should be interpreted as asking, "is there some design pattern that is particularly suited for the problem describe above?)
(Note: I will only accept a vanilla answer, but feel free to provide other answers if you believe they will be helpful).
You could use short-circuit evaluation. You'll still have to write out all of the property names, but I'm not sure there's a way to accomplish this task without doing that.
const myValue = json.age || json.classYear || json.senority || false;
Okay, so if you have a one-dimensional hash table and an array for the priority of keys, then you can use an algorithm like this to select the first one available:
function grab(hash, keyPriority) {
var value;
keyPriority.some(function (key) {
if (hash.hasOwnProperty(key)) { // check if the property exists
value = hash[key];
return true; // break out of loop
}
});
return value;
}
usage:
grab({ c: 3, d: 4 }, ['a', 'b', 'c', 'd']) // 3
You can modify this to work by truthy values, or undefined/null by changing hash.hasOwnProperty(key) to hash[key] or hash[key] != null respectively.
If you are fine with using a bit of JQuery then the following code snippet should do the job I guess.
$.each(JSONObj, function(key, value){
if (!(value === "" || value === null)){
myValue = value;
return false; //to break the loop once a valid value is found
}
});
This will assign the first valid value to your variable myValue and will also exit the loop once a valid value is found.

Comparing objects from key/value array with another object (Key/value)

so here is the situation i currently am having trouble with.
I want to check if a user has permission to view a page, with one single function.
So I have an array with key/values where i store permissions in.
{"authorities":[{"role":"gebruikersbeheer"},{"role":"kijken"},{"role":"plannen"}]};
Stored in service.currentUser, which can be called by using service.currentUser.authorities.
I have a function:
hasPermission: function (permission) {
var role = { "role" : permission };
for(perm in service.currentUser.authorities)
{
var test = service.currentUser.authorities[perm];
if(test === role)
{
return (!!(service.currentUser) && true);
}
}
return false;
}
I created the test variable to debug its value. And the permission parameter has the value 'gebruikersbeheer'.
Now i want to compare the value of the perm key with the role and check if it is true.
Now i have searched along the internet to do so, and i only found solutions which are not viable for me nor implementable.
When i start debugging my perm has an integer value. Why is it not the name of the key? (Which must be "role")
Also, when i use Watch on the role and test variables they are completely the same but still i cant compare them and get a true.
(Dont mind the return statement at this point.)
Also i cannot modify the array. It is returned by spring security this way.
Is there any (nicer) way to check if authorities contains role?
It might be duplicate, but i couldnt find anything for my specific situation.
Cheers.
You currently are check a object with another object, is best check the string with the string, below show an little example of the same function but using the some method from arrays;
var currentUser = {"authorities":[{"role":"gebruikersbeheer"},{"role":"kijken"},{"role":"plannen"}]};
function hasPermission(permission) {
return currentUser.authorities.some(function(v){
return v.role === permission;
});
}
alert("Have permission? "+ hasPermission("gebruikersbeheer"))
service.currentUser.authorities is an array this is why you're getting an integer for perm in for(perm in service.currentUser.authorities).
The other problem is that you can't compare all the properties in the object using === (including prototype properties), so you need to compare explicit the values for the properties... or create a custom function to compare your objects.
You can try with:
hasPermission: function (permission) {
var role = { "role" : permission };
for(perm in service.currentUser.authorities)
{
var test = service.currentUser.authorities[perm];
if(test["role"] === role["role"])
{
return (!!(service.currentUser) && true);
}
}
return false;
}
Hope this helps,
Since you are just concerned with whether something exists or not, you can use the Array.Some function. It still loops through the array, but will stop upon hitting the first instance that is true. Your method is basically doing the same thing already, but this way it a bit cleaner, since it uses the actual elements of the array (instead of an index).
hasPermission: function (permission) {
var authArray = service.currentUser.authorities;
var hasAuth = authArray.some(function(kvp) {
return kvp.role == permission; //function to determine a match
});
return hasAuth;
}

How to access key itself using javascript

I have a JSON like:
var xx = {'name':'alx','age':12};
Now I can read the value of name which is 'alx' as xx[0].name, but how should I retrieve value of 'name' itself? By that, I mean how can I fetch the key at run time?
for (i in xx) {
if (xx[i] == "alx") {
// i is the key
}
}
modified Code (from Victor) taking into account that you might want to look for any other possible string
var search_object = "string_to_look_for";
for (i in xx) {
if (xx[i] == search_object) {
// i is the key
alert(i+" is the key!!!"); // alert, to make clear which one
}
}
You are looking for associative arrays in Javascript. A quick google search suggests the following:
Read this page http://www.quirksmode.org/js/associative.html
and especially this section http://www.quirksmode.org/js/associative.html#link5

Categories

Resources