Comparing data from JSON and input.value - javascript

I am working on small shopping cart project. I have products in JSON.file, also I have input for finding price of products.
I am using class method
question is: this are strings or numbers? -> (3) ['35', '35', '35']
searchItem(data) {
let that = this
searchBtn.addEventListener('click', function(e) {
const input = document.querySelector('.input').value
const findItem = data.filter(function(item) {
if(item.price === input) {
return item
}
}) // this return all data of product so I filtered only prices bellow
const getItem = findItem.map(item => {
return item.price
})
// this give: (3) ['35', '35', '35']
if(input === getItem) {
console.log('same')
} else {
console.log('try it again')
}
// this cond. show me : console.log('try it again')
// HOW TO GET: console.log('same')
e.preventDefault()
})

You can always run a typeof to find out what data types you dealing with
for example
console.log(typeof getItem[0])
also here :
if(input === getItem) {
console.log('same')
} else {
console.log('try it again')
}
you are checking the input variable against a whole array,you have to specify which item of the array to check against like :
if(input === getItem[0]) {
console.log('same')
} else {
console.log('try it again')
}

A quick and straight to your question without the code analysis, Any value gotten from your input is a string and not numbers.
Therefore, if the values of the price you are getting from data are integer, then you will have to consider parsing the values from the input by using the parseInt() method. Example;
const findItem = data.filter(function(item) {
if(item.price === parseInt(input)) {
return item
}
})
Another thing is that getItem is an array so, evaluating with a particular value from input is bound to fail. Therefore, use getItem[0] instead and two "==" instead of "===" just as suggested on the comment.
function searchItem(data) {
let that = this
searchBtn.addEventListener('click', function(e) {
const input = document.querySelector('.input').value
const findItem = data.filter(function(item) {
if(item.price == input) {
return item
}
}) // this return all data of product so I filtered only prices bellow
const getItem = findItem.map(item => {
return item.price
})
console.log(getItem);
// this give: (3) ['35', '35', '35']
if(input == getItem[0]) {
console.log('same')
} else {
console.log('try it again')
}
// this cond. show me : console.log('try it again')
// HOW TO GET: console.log('same')
e.preventDefault()
})
}

Related

Check all values in && comparison?

JavaScript is known to only check the first variable in a && comparison in case the first variable returns false. Is there a way to 'ask' JavaScript to check both variables i.e. when they are methods?
For example: Suppose you have 2 methods that validate 2 separate user inputs:
const validateEmail = value => {
if(value.contains('#')){
setShowEmailError(false);
return true;
}
setShowEmailError(true);
return false;
};
const validatePswd = value => {
if(value !== ''){
setShowPswdError(false);
return true;
}
setShowPswdError(true);
return false;
};
Then check both conditions:
if(validateEmail(email) && validatePswd(pswd)){
//validate entire form and render errors
}
However, the above will not execute the validatePswd method if the first method validateEmail returns false.
Is there a way to check if both values are true and run both methods? Having JavaScript run both methods would be a breeze in some cases.
You can execute them in an array and then accumulate the result with && by reduce function.
const validateEmail = value => {
if(value.includes('#')){
//setShowEmailError(false);
return true;
}
//setShowEmailError(true);
console.log('wrong email')
return false;
};
const validatePswd = value => {
if(value !== ''){
//setShowPswdError(false);
return true;
}
// setShowPswdError(true);
console.log('wrong password');
return false;
};
// you can execute any number of validations within the array.
const result = [validateEmail('something'), validatePswd('')].reduce((acc, f) => acc && f, true);
console.log(result)
UPDATE
Or as #lux suggested using every method.
const validateEmail = value => {
if(value.includes('#')){
//setShowEmailError(false);
return true;
}
//setShowEmailError(true);
console.log('wrong email')
return false;
};
const validatePswd = value => {
if(value !== ''){
//setShowPswdError(false);
return true;
}
// setShowPswdError(true);
console.log('wrong password');
return false;
};
// you can execute any number of validations within the array.
const result = [validateEmail('something'), validatePswd('')].every(r => r);
console.log(result)
I don't know if you are looking for something like this:
const valEmail = validateEmail(email);
const valPsw = validatePswd(pswd);
if(valEmail && valPsw ){
//validate entire form and render errors
}

Check for duplicates in database before pushing item logic in JS

Can please someone let me know what's the issue with this code
I run get ref database and store results in obj, then if obj is empty we push new item. Otherwise I run a loop to see if item already exists.
The code not only doesn't follow any logic, but also push 3 items on third try, 4 on 4th and so on.
This is confusing, why it's not working, Checking for strings if equals I have implemented that not sure about the rest
saveIng = (item) => {
const reference = ref(
database,
"users/" + this.state.user + "/ingredients"
);
get(ref(database, "users/" + this.state.user + "/ingredients"))
.then((snapshot) => {
var obj = snapshot.val();
if (obj === null) {
push(reference, {
name: item,
});
} else {
for (let x in obj) {
var found = obj[x].name == item;
if (!found) {
continue;
} else {
push(reference, {
name: item,
});
}
}
}
})
.catch((error) => {
console.log(error);
});
};

react native cant update state array in function

Im trying to push object into a state array in a function.But i cant, when i debug my array it is still empty..this.state = {
searchArray : [],}
here is my function
doSearch = (textinput) => {
let arrSearch = this.state.searchArray
//iterate model object
this.state.models[this.props.sexeModel].map(
(model) => {
let idmodel = model.id
//check if typed text is included in model name
if(model.nom.includes(textinput.SearchText)){
if(textinput.SearchText.length !== 0) {
//Checking if Search arr is empty
if(arrSearch.length === 0) {
let stateArray = this.state.searchArray
let joined = stateArray.concat(model)
this.setState({ searchArray: joined }) // CANT UPDATE HERE
} else {
arrSearch.map((modelSearch) => {
if(modelSearch.id == idmodel) {
console.log("Do not insert")
} else {
console.log("Insert")
let joined = arrSearch.concat(model)
this.setState({ arrSearch: joined })// CANTE UPDATE HERE
}
})
}
} else {
console.log("include but empty")
this.setState({searchArray:[]}) //CANT UPDATE HERE
}
} else {
console.log("not included")
this.setState({searchArray:[]}) // CANT UPDATE HERE
}
}
)
}
I can update a basic string or int/float state value in this function but not an array.Why ?
Any Ideas ?

How do I ensure an array has no null values?

I would like test my Array (input value) before submit my form.
My array with value :
const fields = [
this.state.workshopSelected,
this.state.countrySelected,
this.state.productionTypeSelected,
this.state.numEmployeesSelected,
this.state.startAt
];
I've try this :
_.forEach(fields, (field) => {
if (field === null) {
return false;
}
});
alert('Can submit !');
...
I think my problem is because i don't use Promise. I've try to test with Promise.all(fields).then(());, but i'm always in then.
Anyone have idea ?
Thank you :)
The problem is that even though you're terminating the lodash _.forEach loop early, you don't do anything else with the information that you had a null entry.
Instead of lodash's _.forEach, I'd use the built-in Array#includes (fairly new) or Array#indexOf to find out if any of the entries is null:
if (fields.includes(null)) { // or if (fields.indexOf(null) != -1)
// At least one was null
} else {
// All were non-null
alert('Can submit !');
}
For more complex tests, you can use Array#some which lets you provide a callback for the test.
Live example with indexOf:
const state = {
workshopSelected: [],
countrySelected: [],
productionTypeSelected: [],
numEmployeesSelected: [],
startAt: []
};
const fields = [
state.workshopSelected,
state.countrySelected,
state.productionTypeSelected,
state.numEmployeesSelected,
state.startAt
];
if (fields.indexOf(null) != -1) {
console.log("Before: At least one was null");
} else {
console.log("Before: None were null");
}
fields[2] = null;
if (fields.indexOf(null) != -1) {
console.log("After: At least one was null");
} else {
console.log("After: None were null");
}
You do not need to use promises unless there is an asynchronous operation (for example if you are getting that array from your server).
If you already have that array you can do something like:
// Using lodash/underscore
var isValid = _.every(fields, (field) => (field!==null)}
// OR using the Array.every method
var isValid = fields.every((field)=>(field!==null))
// Or using vanilla JS only
function checkArray(array){
for(var i = 0; i < array.length ; i ++){
if(array[i]===null){
return false;
}
}
return true;
}
var isValid = checkArray(fields);
// After you get that value, you can execute your alert based on it
if(!isValid){
alert('Something went wrong..');
}
Try this simple snippet
var isAllowedToSubmit = true;
_.forEach(fields, (field) => {
if (!field) {
isAllowedToSubmit = false;
}
});
if(isAllowedToSubmit)
alert('Can submit !');
You can do that without library:
if (fields.some(field => field === null)) {
alert('Cannot submit');
} else {
alert('Can submit');
}
You don't need to use lodash, you can do this in simple vanilla javascript. Simply iterate over each field and if an error occurs set your errors bool to true
let errors = false;
fields.forEach(field) => {
if(field === null || field === '') {
errors = true;
}
});
if (!errors) {
alert('Yay no errors, now you can submit');
}
For an es6 you can use.
const hasNoError = fields.every((field, index, selfArray) => field !== null);
if (!hasNoError) {
alert('yay It works');
};
Have a look at Array.every documentation Array every MDN documentation

How to add value to array after checking another array

I have two arrays as such :
UserGroupUser[{Id:"1",UserId:"2",UserGroupId"1"},
{Id:"2",UserId:"3",UserGroupId"1"},
{Id:"3",UserId:"4",UserGroupId"2"}]
UserGroupId will have values such as 1, 2, 3 etc.
Employee[{EmployeeId:"1", EmpName:"John", Email:"john#example.com"},
{EmployeeId:"2", EmpName:"Mary", Email:"Mary#example.com"},
{EmployeeId:"3", EmpName:"Sarah", Email:"Sarah#example.com"},
{EmployeeId:"4", EmpName:"Jake", Email:"Jake#example.com"} ]
I will store a number in a variable GroupId such as GroupId=1
and what i want to do is check the UserGroupUser table if GroupId 1 matches any rows for key UserGroupId and if there is a match for every UserId the corresponding EmployeeId in Employee table that matches would mean i add a new element called enrolled=true. else if there is not match add a element to Employee enrolled=false.
for eg:
If GroupId is =1 then i want to get the userId of those with the UserGroupId as 1 in the UserGroupUser array and add enrolled:true into the Employee array EmployeeId to those corresponding to the UserId .
This is how i tried to do it..
UserGroupUser.forEach(function (arrayItem) {
if (arrayItem.UserGroupId === GroupId) {
result = Employee.map(function (a, index, array) {
while (arrayItem.UserId === a.EmployeeNo) {
a.enrolled = true;
}
return a;
}
);
}
else {
result = Employee.map(function (a, index, array) {
a.enrolled = false;
return a;
}
);
}
});
what am i doing wrong? how should i do this?
Try this
var userGroup = [{Id:"1",UserId:"2",UserGroupId:"1"},
{Id:"2",UserId:"3",UserGroupId:"1"},
{Id:"3",UserId:"4",UserGroupId:"2"}]
var employees = [{EmployeeId:"1", EmpName:"John", Email:"john#example.com"},
{EmployeeId:"2", EmpName:"Mary", Email:"Mary#example.com"},
{EmployeeId:"3", EmpName:"Sarah", Email:"Sarah#example.com"},
{EmployeeId:"4", EmpName:"Jake", Email:"Jake#example.com"} ]
employees.forEach(function(item){
var found = userGroup.filter(i=>i.UserId==item.Id);
if(found.length>0)
item.enrolled = true
else
item.enrolled = false
})
console.log(employees);
the employees then will contained the enrolled or not try this in your console too
The problem with your code is that when if (arrayItem.UserGroupId === GroupId) { is executed, it changes enrolled to true for the concerned employees but when the else part of this check is executed, it overrides the changes made by the if condition part.
Try this.
UserGroupUser = [{Id:"1",UserId:"2",UserGroupId:"1"},
{Id:"2",UserId:"3",UserGroupId:"1"},
{Id:"3",UserId:"4",UserGroupId:"2"}];
Employee = [{EmployeeId:"1", EmpName:"John", Email:"john#example.com"},
{EmployeeId:"2", EmpName:"Mary", Email:"Mary#example.com"},
{EmployeeId:"3", EmpName:"Sarah", Email:"Sarah#example.com"},
{EmployeeId:"4", EmpName:"Jake", Email:"Jake#example.com"}];
GroupId = "1";
Employee.map(function (emp) {
emp.enrolled = false;
});
UserGroupUser.forEach(function (arrayItem) {
if (arrayItem.UserGroupId === GroupId) {
Employee.map(function (emp) {
if (arrayItem.UserId === emp.EmployeeId) {
emp.enrolled = true;
}
});
}
});
console.log(Employee);

Categories

Resources