Search For Exact Match In JSON With JavaScript - javascript

I have been trying to figure out how have a form submit which then checks all the data in the form against JSON array data to determine if an object which matches all the input is already present. To start, here is my sample JSON data:
[
{
"ASIN":"B0971Y6PQ3",
"price":"13.99",
"email": "test#gmail.com"
},
{
"ASIN":"B077TLGP58",
"price":"13.99",
"email":"test#gmail.com"
}
]
So I am trying to run a for loop which will test whether all the form data already exists as a JSON object. Here's what I currently have:
// Check to see if it's already in asinJSON.json
for(i=0; i<asinJSON.length;i++){
if(asinJSON[i].email == email){
// Email is already in json
if(asinJSON[i].ASIN == inputVal){
// Email && ASIN are already in json
if(asinJSON[i].price == desiredPrice){
// Email, ASIN, Price all match. Duplicate.
console.log('same price found. product already exists.');
break;
}
// If price doesn't match, user wants to update price
console.log('updating price');
// Update price here
// updateJSON();
break;
}
// Existing user wants to add new product.
console.log('product not found');
// Insert product for existing user
// createAndAdd();
break;
}
// New user wants to add a product.
console.log('email not found.');
// insert product for new user
// createAndAdd();
break;
}
How it is now, when trying to test whether it can find the second object, it console.logs "product not found," which I understand is because it passes the first if statement but fails the second with the 1st object in the JSON array.
I'm also assuming it has to do with my break statements, and that something is wrong there. I've also tried return statents and haven't been able to figure it out. I've been self-taught so there are, unfortunately, some things that I have definitely missed along the way. But, I have looked aroung Google and StackOverflow and haven't really been able to find an answer, so here I am.
I'm ready to be schooled in how this logic should be set up to get it to work properly. I appreciate all the feedback in advance!

Use the find() method to search for a matching element.
if (asinJSON.find(({ASIN, price, email: json_email}) =>
ASIN == inputVal && price == desiredPrice && json_email == email)) {
console.log("product already exists");
} else {
console.log("product not found");
}

There are many options, one easy one is to use lodash
const email = <email to find>
const price = <price to find> (however, keep your mind around floating points comparison here...)
const ASIN = < ASIN to find >
if (findIndex(asinJSON, { ASIN, price, email }) > -1) {
// found
}

Related

Search for exact value in object (license check)

So I have a file with multiple objects like this:
{
"order":{
"identifier":"B409908375",
"timeCreated":"2018-11-17T18:27:14.423335",
"totalPrice":10.000000000000000000000000000,
"payer_identity":{
"identifier":"K396677386",
"firstName":"Erika",
"lastName":"Mustermann",
"email":"testbuyer#mail.com",
"isEmailVerified":true,
"countryCode3Letter":"DEU"
},
"paymentProviderId":1,
"runtimeLengthDays":-1,
"runtimeOptionCustomIdentifier":"7fbdc628-893c-4499-844c-7a8c7ecaf325",
"productSku":"nd79z8jinqmkmtewfrb5"
},
"license":{
"productSku":"nd79z8jinqmkmtewfrb5",
"issuedToIdentifier":"K396677386",
"validFrom":"2018-11-17T18:27:21.21126",
"validUntil":"9999-01-01T00:00:00",
"isPermanent":true,
"keyIdentifier":"6b3d646f-cb20-4fc5-b520-e53227379407",
"isActive":true
}
}
I am trying to do a license check, so look for the keyIdentifier and see if it matches an input through a form. The input returns {license: "input"} and the result returns {order: {…}, license: {…}}. So yeah I want to check if input value can be found in the result/object.
I don't know if you aim to write your own function to do this from scratch or you want to use built in functions? If you don't have any preferences, you should be able to achieve this like:
const objects = [{object values>}, ...];
function getKeyIdObject(id) {
return objects.find(current => current.license.keyIdentifier === id);
}
getKeyIdObject ('<insert id here>');
This will return the matching object or null if not found. If you want to adjust what you return, you can also add .map(..) to adjust this.
So yeah I want to check if input value can be found in the result/object.
It sounds like you have no idea what is the key name where license number is being stored. But you have a clear name keyIdentifier contained into license breanch, so value can be easily get buy {}.license.keyIdentifier. If you try to do all that on fly you can just put both responses (input / result) into variables and then check if key is correct like this:
const keyFromInput = // here is what you get from input
const result = // here is {order: {…}, license: {…}}
if (keyFromInput === result.license.keyIdentifier) {
//here is what to do if key is correct
} else {
//here is what to do if key is wrong
}
Hope I got you right and you will find this helpful.

Trying to delete a fields array in firestore but my method is not working

So I am trying to delete the field Notes[1], selectedNote has a value of the selected array I need to delete.
window.addEventListener("load", function load(event) {
document.getElementById("deleteNotes").onclick = function() {
console.log("you did click atleast");
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
let user = firebase.auth().currentUser;
let userInfo = db.collection("Users").doc(user.uid);
userInfo.get().then(function(doc) {
if (doc.exists) {
let selectedNote = document.getElementById("noteSelect")
.selectedIndex;
console.log(selectedNote);
var cityRef = db.collection("Users").doc(user.uid);
cityRef.update({
Notes: FieldValue.delete().arrayRemove(selectedNote)
});
}
});
}
});
};
});
So I am trying to use this
cityRef.update({
Notes: FieldValue.delete().arrayRemove(selectedNote)
});
to delete the selectedNote which is the array 1 for example inside of Notes. I don't want the entire Notes field deleted but just the selected array inside the Notes field. For some reason I am struggling to get it working. Any help would be appreciated <3
Firebase arrays doesn't use a indexes for their arrays, instead they require the value of the array entry. this does mean you can't get away with duplicated data.
you will have to fetch the array "Notes" first and return its value from its index
Although, I have heard that the arrays can come back out of order because they don't rely on an index.
change this line;
Notes: FieldValue.delete().arrayRemove(selectedNote)
to this;
Notes: FieldValue.delete().arrayRemove(doc.data().Notes[selectedNote])
I would recommend you pull the value of the array from a stored variable locally to ensure the values match pre and post edit.

Else works even if "if" works

I'm getting value from SQLite3 database and put it to if-else, but for some reason and "if", and "else" works. My code:
// can_ask = 1 - user can ask
// can_ask = 0 - user cannot ask
// Getting user
db.each(`SELECT ${+msg.senderId} AS user_id, can_ask FROM users WHERE user_id = ${+msg.senderId}`, function(err, user) {
if(user.can_ask == 1) {
console.log("Works nice!");
db.run(`REPLACE INTO users(user_id, can_ask) VALUES (${+user.id}, 0);`) // Making "can_ask" a 0.
} else {console.log("You can't ask!")}
})
And if user can ask it returns:
Works nice!
You can't ask!
If cannot:
You can't ask!
You can't ask!
Why else is always true? How I can fix this?
Probably you are getting more than one results from the query
Do a GROUP BY user_id so you will only have one id of each row.

How to add to use push() with a specified key instead of default key on firebase

So I'm trying to store user information in a database using Firebase, which includes their email, ID, and associated group.
Each time a new user creates an account their data is saved in the parent node Managers
Here is my code so far,
var manRef = firebase.database().ref('Managers');
function saveManage(sEmail, uid, society){
manRef.push({
ManagerID : uid,
Email : sEmail,
Society : society
})
}
For variables in the function saveManage are gathered from entries on a form, I want to be able to push a new entry into the node Managers but have the highlighted key in the image be set as a predefined value, such as the uid so that it is easier for me to reference the individual entries later
It sounds like you just want to set() the value at your predefined location instead of using push(), which always uses its own algorithm for generating the key.
manRef.child(uid).set({
ManagerID : uid,
Email : sEmail,
Society : society
})
}
I would do something like below to make this function robust. Note, I like to .toLowerCase() properties before storing them. This way you can now call this same function even if you want to update only their email and leave the rest alone.
var managersRef = firebase.database().ref('managers');
function saveManager(email, uid, society){
var obj = {};
if (uid !== undefined){
if (email !== undefined){
obj["email"][email.toLowerCase()];
}
if (society !== undefined){
obj["society"][society.toLowerCase()];
}
managersref.child(uid).update(obj);
} else {
console.log("uid required") //or throw an error
}
}

Recursicely call data in a mongodb with node

I am creating a login system and i want to implement a username system automatically after registration with the user first-name and last-name. Everything is working fine but in the case if the registered user with the same first-name and last-name is already in the system i want to concatenate a incrmental number to it.
Example if : firstname:Badmus Lastname:Kabiru is in the system as badmus.kabiru and the newly registered user is also named so the new user username will be badmus.kabiru.1 the next will be badmus.kabiru.2.
My code sample are.
assignUserTrendname: function(req_username, callback){
let userNewname = fetchUserName(req_username);
let inc = 1, newlyAssignUsername;
userNewname.then((usernames) => {
console.log(req_username+" ...................... "+usernames); //The data from the database is loging out
if (usernames.atusername == null || usernames.atusername == undefined) {
newlyAssignUsername = req_username;
console.log("Assign automaticaly "+ newlyAssignUsername);
} else {
newlyAssignUsername = req_username;
console.log(`Username Result is DB: ${usernames.atusername} Req: ${newlyAssignUsername} Search ${inc}`);
if(usernames.atusername.toString() == newlyAssignUsername.toString()){
console.log("User name exit and inc is "+ inc);
inc++;
newlyAssignUsername = `${req_username}.${inc}`;
console.log("New search..."+ newlyAssignUsername);
fetchusernames(newlyAssignUsername); // These is not fetching from the database
}
newlyAssignUsername = `${req_username}.${inc}`;
}
console.log("Assigned is ......"+ newTrendname);
callback(null, newTrendname);
})
.catch((err)=> {console.log(err); throw err;});
}
function fetchUserName(trendname){
return Trender.getUserByTrendname(trendname);
}
If i am taking the wrong route please let me know.
Thanks.
In the scenario that your.username already exists you can search your Users with a regex pattern: ((?:your\.username)\d+$). This will get all records that match: your.username{num} where {num} is any number. If your username's are formatted as your.username.123 the pattern would be: ((?:your\.username\.)\d+$).
Assuming this returns an array, existing_users, you can count the records, since you'll always be incrementing by one, which will give you your next incremented number. Pseudo code:
let inc = existing_users.length + 1;
However, in the scenario that you delete a user your count is going to be off. You would need to loop over your existing_users and extract the number at the end and only keep the largest number.
let largest_num = 0;
existing_users.forEach(user => {
let num = user.match(/\d+$/);
if ( num != null && parseInt(num[0]) > largest_num ) {
largest_num = num[0];
}
});
Then you could do the same as above: let inc = largest_num + 1 and add that to your your.username string.
I do not know what library/framework you're using to search your MongoDB so I cannot write a query and function snippet.
We cannot write your code for you. A general regex has already been given that could be a potential way to solve your problem. If you go that route you can make use of the $regex operator. If you were to store the increment of the username as a separate field you could also sort by that to get the max value as well.
Here is an example of that:
db.users.find({
username: {
$regex: < Your Regex Here >
}
}).sort({
usernameIncrement: -1
}).limit(1);
Please see:
http://mongoosejs.com/docs/queries.html
https://docs.mongodb.com/manual/reference/operator/query/regex/
https://docs.mongodb.com/manual/reference/method/cursor.sort/

Categories