How To Check For One Json Object Being Present In Another
I have two sets of data in a JSON (data.json) as below : UP = [{'password': 'jhonjhon', 'username':'jhon'}, {'password': 'juliejulie', 'username':'julie'}, {'password': 'blakeblak
Solution 1:
To check if password
is same as in JSON by user, you have to loop that JSON array and check values:
for (var i = 0; i < UP.length; i++) {
if (UP[i].username == x && UP[i].password == y) {
for (var j = 0; j < Admins.length; j++) {
if (Admin[i].Admin == x) {
//It's correct logins, do something
}
}
}
}
SECURITY
Never put passwords in user accessible location, always use back-end validation, always encode your passwords. Your approach is VERY VERY insecure. I always can check JSON source file and see what logins I can put to login as admin
Solution 2:
Your should loop through the JSON object and check the uid
is present or not.
adminFlag
will set to true if the x
is present in Admins
.
Try the code given below:
functionfinalCheck(){
var adminJSON = JSON.parse(Admins), // since Admins is string, parse to Json first
length = adminJSON.length,
x = document.forms["myForm"]["uid"].value,
y = document.forms["myForm"]["pwd"].value,
adminFlag = false;
// for loop to find admin is present or notfor(var i = 0; i < length; i++){
if(adminJSON[i].Admin == x){
adminFlag = true;
break;
}
}
}
Solution 3:
I suppose that this task is for a learning purpose. Please never do this in production. You could play with this sample code. There are a lot of smarter solutions but in my opinion this would help you to understand the basics.
varUP = [{"password": "jhonjhon", "username":"jhon"}, {"password": "juliejulie", "username":"julie"}, {"password": "blakeblake", "username":"blake"}];
varADMINS = [{"Admin":"jhon"}, {"Admin":"julie"}];
functionfinalcheck()
{
var x = 'jhon';
var y = 'jhonjhon';
for(var i = 0; i < UP.length; i++)
{
if (UP[i].password == x && UP[i].username == y)
{
console.log(y + ' has access!');
for (var j = 0; j < ADMINS.length; j++) {
if (ADMINS[j].Admin == y)
{
console.log(y + ' is Admin');
}
}
}
}
}
Post a Comment for "How To Check For One Json Object Being Present In Another"