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

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;
}

Related

Type of this is always object while checking for a valid Javascrip Object

I wrote a Prototype function in javascript to determine whether an entity is a valid Javascript object or not. Something like following
// Check if Object is Valid & Have at least one element
Object.prototype._isValidObject = function () {
return this && typeof this === 'object' && !Array.isArray(this) && Object.keys(this).length >= 1;
};
The problem is it is returning TRUE for most of the values, like even for string, cause this is treated like an object for any value, like arrays, strings or json etc. There may be other ways to do this, but I need to make a prototype function for this. Please determine the correct way to Determine whether a value is a valid Javascript object having atleast one item. Thanks
EDIT
By Valid Javascript / JSON Object I mean something like this:
{
id:100,
name:'somename',
email:'maiL#mail.com'
}
To be more precise following is what I want:
const j = {id:100,name:'somename', email:'maiL#mail.com'};
const s = "{id:100, name:'somename', email:'maiL#mail.com'}";
j._isValidObject(); // Should return true
s._isValidObject(); // Should return false
const j is valid for me cause it is an object having key-value pairs. const s is invalid for me cause it's a string representation of an object, not the object itself. const s can be converted to valid Object like const j, but right now const s is just a string.
EDIT
I have found a solution, and posted it in answers. Though I am not marking it as accepted answer since I'm not sure whether it's the best way to do it. If somebody has a better solution, please post it. Thanks
I have found a solution, though I am not marking as accepted answer since I'm not sure whether it's the best way to do it. If somebody has a better solution, please post it. Thanks
// Check if Object is Valid & Have at least one element
Object.prototype._isValidObject = function () {
return this
&& !(this instanceof String)
&& !Array.isArray(this)
&& Object.keys(this).length >= 1;
};

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.

Get a value from URL and create a Javascript function

I am new on this website, and I am also new at Javascript.
What I would do is get a value from a link, eg:
http://bricks.couponmicrosite.net/JavaBricksWeb/LandingPage.aspx?O=107905&C=MF&CPT=qwbc74g7HdLtKVVQ1oNe&P=test&tqnm=td3ffdn764156741
I need to take this value: O=107905, if it is only one code I need to run a file (file A),
if it look like this: O=107905~107906, then I need to run a different file (file B).
What I thought is create a function with javascript where if it is (~) is missing, then will be used the file A, if there is one or more than one of (~) then the file B will start to work.
Many thanks in advance!
Well. We really do encourage you to provide your own code first before providing solutions, but this is a fairly simple problem in javascript. Here's my take on it.
The first problem you have to solve is actually getting the query string parameters in a meaningful format. Here I create an object that uses the query string keys as the object keys (IE 9+ only because of the forEach)
var tmpObject = {}
location.search.substr(1).split('&').forEach(function(item){
var o = item.split('=');
tmpObject[o.shift()] = o.shift();
});
Then it's just a matter of making sure the query string contained the target object (in this case "O") and determine if there is more than one.
if(tmpObject.hasOwnProperty('O') && tmpObject.O.split('~').length > 1) {
console.log('return multiple files');
} else {
console.log('return one file');
}
Try this
var url = "http://bricks.couponmicrosite.net/JavaBricksWeb/LandingPage.aspx?O=107905&C=MF&CPT=qwbc74g7HdLtKVVQ1oNe&P=test&tqnm=td3ffdn764156741";
var search = url.substring(url.indexOf("?")+1);
var map={};
search.forEach(function(val){var items=val.split("="); map[items[0]]=items[1];});
if (map["O"].indexOf("~") != -1)
{
//O value has ~ in it
}
else
{
//O has no ~ in it
}
Possible solution to get the paramter would be there : How to get the value from the GET parameters?
Once you have the parameter value, you can for sure look if you find '~' with String.prototype.indexOf.
String.prototype.indexOf returns the position of the string in the other string. If not found, it will return -1.

Maybe monad in JavaScript

In the examples for monads.maybe on npm we have:
function find(collection, predicate) {
for (var i = 0; i < collection.length; ++i) {
var item = collection[i]
if (predicate(item)) return Maybe.Just(item)
}
return Maybe.Nothing()
}
Can someone explain what Maybe.Just(item); and Maybe.Nothing() are actually doing?
Put another way; are monads essentially objects used as return values that implement specific interfaces that enable the definition of a sequence of function invocations?
Maybe is used to represent an operation that might fail.
In the case of this function, you return Just(the element) if an element fulfills the predicate, else, you return Nothing to show that it had "failed" (in this case, none of the elements fulfill the predicate).
It's preferred to just returning a null because the return type explicitly shows that it can fail, and the answer can be pattern matched against.
Monads are abstract containers with an API to operate on the data contained within. In the instance of the Option monad I think of it as a giftbox that either has a gift or is empty. Wrapping your data in a Maybe.Just() signifies that this container does infact contain data, while at the same time it maintains the returned value as a Maybe. The caller of your find() method can then do this:
var userPredicate = function(user) { return user.name === 'billy bob'; };
var users = collections.getUsersCollection();
var maybeData = find(users, userPredicate);
if(maybeData.isJust()) {
// there was data...do something with it
} else {
// no data...do something else
}
On the other hand, Maybe.Nothing() indicates the absence of data (the else part in the example above). Ideally, you would wrap your data within like so: var maybeData = Maybe(data) and then operate on this, pass it around etc. This is a signal to anyone receiving this object that they need to handle the case of missing data consciously.
Disclosure: I'm working on a similar library called Giftbox that has a richer API. Take a look at the readme there for some more explanations to help you understand what the Option monad is and how to use it effectively.
Here's an article describing Monads, Applicatives and Functors that might be useful to you.

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