How to add value to array after checking another array - javascript

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

Related

React object property assignment only works the first time

For the following code, parameters are js objects whose structures are initialized as follows:
statePiece = {
field_name: { disabled: false, exampleValue: "arbitrary" },
field_name2: {
/* ... */
},
field_nameN: {
/* ... */
}
};
userField = "field_name_string";
sesarValues = {
format: "one2one",
selectedField: "latitude",
disabledSelf: true,
addField: 0
};
This function works correctly and returns the modified statePiece as returnTemp the first time a particular statePiece.field_name is modified
export let setUserField = (statePiece, userField, sesarValues) => {
console.log("set user field", userField, "set mappval", sesarValues);
var temp = { ...statePiece }; //(this.state.fields[each].mappedTo != null) ? (this.state.fields[userField].mappedTo) : [];
var XUnit = statePiece[userField];
if (typeof userField != "string") {
console.log("not string");
for (var each of userField) {
if (sesarValues) {
temp[each].mappedTo = sesarValues.selectedField;
temp[each].disabled = true;
} else {
temp[each].disabled = !temp[each].disabled;
delete temp[each].mappedTo;
}
}
} else {
//is string
console.log("is string");
console.log(XUnit);
if (sesarValues) {
if (XUnit.disabled === true) XUnit.disabled = false;
console.log("1");
console.log(XUnit);
XUnit.disabled = true;
console.log(XUnit);
XUnit.mappedTo = sesarValues.selectedField;
} else {
console.log("2");
temp[userField].disabled = !temp[userField].disabled;
delete temp[userField].mappedTo;
}
}
let returnTemp = { ...temp, [userField]: XUnit };
console.log("set UF debug ", returnTemp);
console.log(returnTemp["FACILITY_CODE"]);
return returnTemp;
};
But after that, changing the statePiece.userField.mappedTo value fails to alter the object property. Or at least alter it permanently. When I console log the returnTemp variable, I see the entry has lost its mappedTo entry(as should happen) without it being replaced with the new userField.
However, when I console.log(returnTemp[userField]) it shows the entry values with the expected mappedTo key: value pair.
Not sure what's going on here.
From the usage of userField, I can work out that it could be an Array or a String.
However you have done something curious with it in the following expression:
var XUnit = statePiece[userField];
Given userField is a String, the above expression is fine.
However, where it is an array, XUnit will be undefined.
Also doing the same where userField is an Array in the following line means that you're setting the userField.toString() as a key mapped to undefined.
let returnTemp = { ...temp, [userField]: XUnit };
I'd assign XUnit where the condition checks out that userField is a String and just return temp.
else {
//is string
var XUnit = statePiece[userField];
//...
}
return temp;

AngularJS check condition and return true or false

I have html like this :
<td><span ng-if="isuser(user) == false" type="button" >not allowed</span> </td>
the above html is displayed only if the function isuser(user) return false.
I have an array like this :
$scope.list = ["456", "111", "459"];
Now the user object has an array called id. This id array contains a number key whose value can be 456,111 or 459 and sometimes it may be empty also.
The user object :
{"name":"pravin","status":"Live","id":[{"number":"111"}],"msg":"test"}
Here is the isuser function :
$scope.isuser = function(user) {
for (var i = 0; i < $scope.list.length; i++){
var exists = user.id.find(({number}) => number === $scope.list[i]);
}
if (exists)
return true;
else
return false;
};
but this always returns false.
I want the for loop to check if none of the values of the number key exists in the list array and then only return false.
How do I do it?
The issue is that the below statement
var exists = user.id.find(({number}) => number === $scope.list[i]);
updates every time the exists variable and always you'll get the last change.
One approach could be using some method by passing a callback function as argument.
$scope.isuser = function(user) {
var exists = user.id.some(({number}) => $scope.list.includes(number));
return exists;
}
Try this it will help you
$scope.isuser = function(user) {
var exists = false;
for (var i = 0; i < $scope.list.length; i++){
exists = user.id.find(({number}) => number === $scope.list[i]);
}
if(i==$scope.list.length-1){
if (exists)
return true;
else
return false;
}
loop };

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 ?

verifying If an object is present in the session's array

here I'm pushing product_detail to an empty array product. At first I'm checking if the array is empty, If so the json data is pushed into the array and updated with session. If not I want to verify if the there exists an object with the id, if so it wont push it. but the condition is not becoming true. Dont know what I'm missing or I'm putting the condition wrongly
var product_details = {
product_id: product._id,
user_id: user_id,
};
if (product.length !== 0) {
if (req.session.product.forEach(function(data) {
(data.product_id == req.params._id)
})) {
return res.send("product already present ");
}
product.push(product_detail);
req.session.product = product;
return res.send(req.session.product);
}
product.push(product_detail);
req.session.product = product;
console.log(req.session);
return res.send(req.session.product);
});
Simply change your nested condition to:
var arrayTrue = true;
req.session.product.forEach(function(data) {
if(data.product_id == req.params._id){
arrayTrue = false;
}
});
if(arrayTrue){
// Doesn't exist...
}
else{
return res.send("Product already present");
}

If ID exists in javascript array with angularjs

Okay, I'm done searching and trying code blocks that don't work. This is what I got.
I'm building an array when I click on an image.
invoices.addItem = function(id) {
var itemRef = new Firebase(fbUrl+'/items/'+id);
itemRef.once("value", function(snapshot) {
invoices.newInvoiceItems.push({
'id' : id,
'name' : snapshot.val().name,
'price' : snapshot.val().prices.sale,
'qty' : '1'
});
});
}
I want to check to see if the ID passed through when the image is clicked again already exists in the array, if it does increase quantity.
All I'm asking for is a simple way to check if the id exists, if it does return true else return false.
if(id exists)
{
return true;
}
return false;
How do I get the id exists working!?!?!?!?!?!?!?!
UPDATE
This is everything I have:
invoices.addItem = function(id) {
if(invoices.checkItem(id))
{
var index;
for (index = 0; index < invoices.newInvoiceItems.length; ++index) {
if(invoices.newInvoiceItems[index].id === id)
{
var qty = invoices.newInvoiceItems[index].qty;
invoices.newInvoiceItems[index].qty = qty++;
}
else
{
return false;
}
}
}
else
{
var itemRef = new Firebase(fbUrl+'/items/'+id);
itemRef.once("value", function(snapshot) {
invoices.newInvoiceItems.push({
'id' : id,
'name' : snapshot.val().name,
'price' : snapshot.val().prices.sale,
'qty' : '1'
});
});
}
}
invoices.removeItem = function(index) {
invoices.newInvoiceItems.splice(index, 1);
}
invoices.checkItem = function(id) {
var index;
for (index = 0; index < invoices.newInvoiceItems.length; ++index) {
if(invoices.newInvoiceItems[index].id === id)
{
return true;
}
else
{
return false;
}
}
}
Let's say I have two items Item A and Item B. If I click on Item A it adds it to the array. Then click it again and it won't add it but only increases qty one time. Now if I click on Item B without refreshing the page mind you, it adds it over and over and over again each time I click on Item B.
I've console logged the id getting returned and it is always the same one, even though each item has it's own ID.
You can use Array.prototype.filter to quickly and easily find an item in an array. If the item is found... then you know it exists.
var existingItem = invoices.newInvoiceItems.filter(function(item){
return item.id === id;
})[0];
if(existingItem ){
++existingItem.qty
}else{
//do your firebase thing...
var itemRef = new Firebase(fbUrl+'/items/'+id);
itemRef.once("value", function(snapshot) {
invoices.newInvoiceItems.push({
'id' : id,
'name' : snapshot.val().name,
'price' : snapshot.val().prices.sale,
'qty' : 1
});
});
}

Categories

Resources