Having some problems with a json array - javascript

exports.equipp = function(user, User, msg) {
var itemname = msg.content.slice(8);
User.find({id: user.id}, function(err, usser) {
for(i = 0; i < usser[0].inventory.length; i++) {
if (usser[0].inventory[i].name == itemname) {
var Item = usser[0].inventory[i];
for (j = 0; j < usser[0].equipped.length; j++) {
if (Item.type == usser[0].equipped[j].type) {
}
if (j == usser[0].equipped.length -1) {
}
}
} else {
if (i == usser[0].inventory.length -1) {
msg.reply("You dont have that Item");
}
}
}
})
}
I'm having some porblems with it at the end at the if (j == usser[0].equipped.length -1) it never goes through and hence never adds an item to a empty inventory. I have items which atm only contain Name, Dmg, and Type im checking if the types match then if they do i add the item to the equipped array and remove it from the items array and vice versa for the item already equipped and when there is no item with that type in the array i need to just add it and remvoe it from the other array but my code fails at the point stated above an array of json objects {
"type": "Healm",
"armor": 4,
"name": "Starter Healm"
},

Instead of this :
for(i = 0; i < usser[0].inventory.length; i++) {
if (usser[0].inventory[i].name == itemname) {
var Item = usser[0].inventory[i];
// rest of code ...
} else {
if (i == usser[0].inventory.length -1) {
msg.reply("You dont have that Item");
}
}
}
Do:
for(i = 0; i < usser[0].inventory.length; i++) {
if (usser[0].inventory[i].name == itemname) {
var Item = usser[0].inventory[i];
// rest of code ...
}
}
if (!Item) {
msg.reply("You dont have that Item");
}
The determining factor whether you found the item is that you have defined Item. It after the loop you find that Item was not set, you know the item was not in the list. This obviously also works when the list is empty.

Related

JQuery and Bootstrap based toaster

In my HTML page i have table in which each row, there is a check box.
My requirement is if more then one row is selected i.e. if the array length is 2, a toaster message has to be shown.
I got a use case there and it is,
if i select 2 rows(array length is 2), message is showing .
Then select 3rd row(array length is 3) and again deselect 3rd row(array length is 2 again).
Now also it shows the message. Here i don't want that toast.
My approach is :
$scope.toggleOne = function () {
if ($scope.selectedUsers.length === 2) {
showMessage();
}
for (var j = 0; j < $scope.users.length; j++) {
if (!$filter('filter')($scope.selectedUsers, $scope.users[j].id, true).length) {
$scope.selectAllCheckboxOfUsers = false;
return;
}
}
$scope.selectAllCheckboxOfUsers = true;
}
If you want to display the message just when going from 1 selected to 2 selected, you can check for that:
var previousSelectedNum = 0;
$scope.toggleOne = function () {
if ($scope.selectedUsers.length === 2 && previousSelectedNum === 1) {
showMessage();
}
// ...
previousSelectedNum = $scope.selectedUsers.length;
}
You can use a flag such as,
var isMessageShown = false;
Then in your function use as,
$scope.toggleOne = function () {
if($scope.selectedUsers.length === 1){
isMessageShown = false;
}
if ($scope.selectedUsers.length === 2 && !isMessageShown) {
isMessageShown = true;
showMessage();
}
for (var j = 0; j < $scope.users.length; j++) {
if (!$filter('filter')($scope.selectedUsers, $scope.users[j].id, true).length) {
$scope.selectAllCheckboxOfUsers = false;
return;
}
}
$scope.selectAllCheckboxOfUsers = true;
}

Execute the else statement if none of the items are found

I have this for loop, and I would like to execute the else in the for loop only if none of the if conditions are met. The for loop runs until every item in the database has been checked. If none of the items in the database matches the user input then I want to run the else.
Right now, it runs the else right after the first try which means if the item matches is in the last row, it will just throw it in the error page since it stops the evaluation at the first iteration.
for(var i=0; i< rows.length; i++) {
if (rows[i].hashtag == userEnteredHashtag) {
// Display the choose Box page
res.render('chooseBox', {});
}
else {
// Display the invalid hashtag page
res.render('invalidHashtag', {});
}
}
Just move the else portion outside of the loop and execute it based on a flag
var wasFound = false;
for (var i = 0; i < rows.length; i++) {
if (rows[i].hashtag == userEnteredHashtag) {
// ...
wasFound = true; // set the flag here
}
}
if (!wasFound) {
res.render('invalidHashtag', {});
}
So add a check outside.
var hasMatch = false;
for (var i = 0; i < rows.length; i++) {
if (rows[i].hashtag == userEnteredHashtag) {
// Display the choose Box page
res.render('chooseBox', {});
hasMatch = true;
}
}
if (!hasMatch) {
// Display the invalid hashtag page
res.render('invalidHashtag', {});
}
Create a variable to track whether your condition has been met:
var isValid = true;
for(var i=0; i< rows.length; i++) {
if (rows[i].hashtag != userEnteredHashtag) {
isValid = false
}
}
isValid ? res.render('chooseBox') : res.render('invalidHashtag')
Another way to do it is to use filter and forEach.
var rows = [{hashtag: '#a'}, {hashtag: 'b'}, {hashtag: 'c'}];
var userEnteredHashTag = '#a';
var matchingRows = rows.filter(row => row.hashtag === userEnteredHashTag);
if (matchingRows.length) {
matchingRows.forEach(row => console.log(row));
} else {
console.log('invalid');
}

for outer and inner loops using arrays in Javascript

Ive been using a azure mobile service back end to manipulated data before it is queried by an app. I have a feed that people can subscribe to an item and get the information from item. the link between the user and the items is in a new table that contains the userid and the itemid. i then do a for loop to find the each items matching itemid and then do an inner for loop to find all of the items details and take them and put them into a new array for sending.
It only seems to be working when i have the request respond after the inner loop like this. However i only get the item details for one of the subscribed items.
var itemfeedcollection = [];
var useritemconnections = tables.getTable('UserItemConnections');
useritemconnections.where({ username : user.userId }).read(
{
success: function(results)
{
if (results.length > 0)
{
for (var itemconnection = 0; itemconnection < results.length; itemconnection++)
{
var items = tables.getTable('Items');
items.where({ itemid : results[itemconnection].itemid }).read(
{
success: function(itemsresults)
{
if (itemsresults.length > 0)
{
for(var item = 0; item < itemsresults.length; item++)
{
itemfeedcollection.push(itemsresults[item])
}
request.respond(statusCodes.OK, itemfeedcollection);
}
else
{
request.respond(400, "We couldn't find any item details for the item you are subscribed to");
return;
}
}
});
}
}
else
{
request.respond(400, "You are not subscribed to any items");
return;
}
}
});
But if i move the request respond to after then outer loop where its suppose to be I get nothing at all. I would think i would at least get one item.
var itemfeedcollection = [];
var useritemconnections = tables.getTable('UserItemConnections');
useritemconnections.where({ username : user.userId }).read(
{
success: function(results)
{
if (results.length > 0)
{
for (var itemconnection = 0; itemconnection < results.length; itemconnection++)
{
var items = tables.getTable('Items');
items.where({ itemid : results[itemconnection].itemid }).read(
{
success: function(itemsresults)
{
if (itemsresults.length > 0)
{
for(var item = 0; item < itemsresults.length; item++)
{
itemfeedcollection.push(itemsresults[item])
}
}
else
{
request.respond(400, "We couldn't find any item details for the item you are subscribed to");
return;
}
}
});
}
request.respond(statusCodes.OK, itemfeedcollection);
}
else
{
request.respond(400, "You are not subscribed to any items");
return;
}
}
});
I am also curious if this is good practice to link items like this. I would also like to add that there maybe up to a few thousand itemconnections meaning that it would do a getTable for each of them. is that a bad thing?
It appears i was right and narrowed it down to the request respond being out side of the items results function. So i called both tables and then did my for loops in the results function then pushed each item to the array and now it is working correctly like this.
var itemfeedcollection = [];
var useritemconnections = tables.getTable('UserItemConnections');
useritemconnections.where({ username : user.userId }).read(
{
success: function(useritemconnectionsresults)
{
if (useritemconnectionsresults.length > 0)
{
var items = tables.getTable('Items');
items.read(
{
success: function(itemsresults)
{
if (itemsresults.length > 0)
{
for (var itemconnection = 0; itemconnection < useritemconnectionsresults.length; itemconnection++)
{
for (var item = 0; item < itemsresults.length; item++)
{
if (useritemconnectionsresults[itemconnection].itemid == itemsresults[item].itemid)
{
itemfeedcollection.push(itemsresults[item]);
}
}
}
request.respond(200, itemfeedcollection);
}
else
{
request.respond(400, "Where have all the items gone");
return;
}
}
});
}
else
{
request.respond(400, "You are not subscribed any items");
return;
}
}
});
This is good becuase now I dont have to call the items table thousands of times.

Javascript: Pushing items to an Array doesn't work

I'm basically trying to loop through an array to check if an item already exists:
If the the item exists, remove it
If the item does not exist, push it to the array
However my code only allows me to add one item only. It ignores every other value I'm trying to add.
var inclfls = []; //new empty array
function addfile(val) {
if (inclfls.length != 0) {
for (var i = 0; i < inclfls.length; i++) {
if (inclfls[i] == val) {
a.style.background = "#999";
inclfls.splice(i, 1); //remove it
}
else {
a.style.background = "#2ECC71";
inclfls.push(val); //push it
}
}
}
else {
a.style.background = "#2ECC71";
inclfls.push(val);
}
alert(inclfls.length);
}
What am I doing wrong?
with array methods, its much simpler:
function addfile(val) {
var index=inclfls.indexOf(val);
if(index===-1){
inclfls.push(val);
a.style.background = "#999";
}else{
inclfls.splice(index,1);
a.style.background = "#2ECC71";
}
}

Removing Groups within an Array in Kineticjs

I am trying to remove elements of an array which contains either Groups(containing shapes) or simply Shapes(line, Rect, Circle etc) as its elements. My function is something like below:
deleteSelectedShape = function () {
var i,
shapeObj,
selectedObjects = currentContext.getSelectedObjects(),
shapeLayer = currentContext.getShapeLayer();
if (selectedObjects && selectedObjects.length > 0) {
for (i = 0; i < selectedObjects.length; i += 1) {
shapeObj = selectedObjects[i];
// shapeObj.remove(); results same error as mentioned at last
if (shapeObj.nodeType === "Group") {
shapeObj.destroyChildren();
}
else{
shapeObj.destroy();
}
}
}
selectedObjects = [];
shapeLayer.draw();
};
I tried this also
if (shapeObj.nodeType === "Group") {
var childs = [];
childs = shapeObj.getChildren();
for (var j = 0; j < childs.length; j++) {
childs[j].remove();
}
}
else{
shapeObj.remove();
}
}
}
Here Individual shapes are getting deleted but if there is group in array, it is giving error :
TypeError: this.getParent(...) is undefined in Kineticjs file
Please suggest me proper idea. Thank you !!!
One problem: When removing items from an array, you have to iterate through that array in reverse.
var i=selectedObjects.length-1;
while( i-- >=0 ){
var shapeObj = selectedObjects[i];
if (shapeObj.nodeType === "Group") {
shapeObj.destroyChildren();
}else{
shapeObj.destroy();
}
}

Categories

Resources