push does not works inside if statement - javascript

I have the code below, but items.push does not work when it is inside the if statement. If uncomment the line before ending } then items.push works as expected.
for (i = 0; i < len; i += 1) {
row = resultexpense.rows.item(i);
t.executeSql('SELECT * FROM expensepayments WHERE Barcode = ?',
[row.barcode],
function(t, resultpaid) {
var myrowpaid,
myrowpaidlen;
myrowpaidlen = resultpaid.rows.length;
alert(myrowpaidlen); //alerts 1
if (myrowpaidlen > 0){
myrowpaid = resultpaid.rows.item(0);
alert(row.amount); //alerts 90
alert(myrowpaid.Amount); //alerts 50
if (row.amount > myrowpaid.Amount){
alert(row.amount- myrowpaid.Amount); //alerts 40
items.push('<li>' + row.description + '</li>');
}
} else {
items.push('<li>' + row.description + '</li>');
}
});
// items.push('<li>' + row.description + '</li>');
}

I am not really sure what typeof your variable is, is it number or just a string?
if typeof row.amount == "string" or typeof myrowpaid.Amount == "string" then the if condition not going to execute.
to be sure, your variable is number type, use parseInt() function to convert into number
if (parseInt(row.amount, 10) > parseInt(myrowpaid.Amount, 10)){
alert(row.amount- myrowpaid.Amount); //alerts 40
items.push('<li>' + row.description + '</li>');
}
if you not already deceleared the items variable then, add var items = []; before use of items variable

Related

Looping over JavaScript object and adding string to end if not the last item

{
field_country: ["England", "Netherlands", "India", "Italy"],
field_continent: ["Europe"],
field_group: ["Building", "People", "Landscape"
}
I want to loop over each item and return the key and the array together with ending 'OR' for example:
field_country: "England" OR field_country: "Netherlands"
The last item should not end with 'OR' in the loop. I am not sure what the best process is for this using vanilla JS. So far my code is as follows:
Object.keys(facets).forEach(function(facetKey) {
if (facets[facetKey].length > 1) {
facetResults = facets[facetKey];
for (var i = 0; i < facetResults.length; i ++) {
if (i == 1) {
filter = "'" + facetKey + "'" + ":'" + facetResults[i] + " OR";
return filter;
} else {
filter = "'" + facetKey + "'" + ":'" + facetResults[i];
}
}
} else {
filter = "'" + facetKey + "'" + ": " + facets[facetKey] + "'";
return filter;
}
});
I would be very grateful for any assistance.
Thanks in advance.
You can do something like this with Object.entries and Array.reduce if you would like to get the final result in the form of an object:
const data = { field_country: ["England", "Netherlands", "India", "Italy"], field_continent: ["Europe"], field_group: ["Building", "People", "Landscape"] }
const result = Object.entries(data).reduce((r, [k, v]) => {
r[k] = v.join(' OR ')
return r
}, {})
console.log(result)
It is somewhat unclear what is the final format you need to result in but that should help you to get the idea. If ES6 is not an option you can convert this to:
const result = Object.entries(data).reduce(function(r, [k, v]) {
r[k] = v.join(' OR ')
return r
}, {})
So there are is no arrow function etc.
The idea is to get the arrays into the arrays of strings and use the Array.join to do the "replacement" for you via join(' OR ')
Here's the idea. In your code you are appending " or " at the end of your strings starting at index 0. I suggest you append it at the the beginning starting at index 1.
var somewords = ["ORANGE", "GREEN", "BLUE", "WHITE" ];
var retval = somewords[0];
for(var i = 1; i< somewords.length; i++)
{
retval += " or " + somewords[i];
}
console.log(retval);
//result is: ORANGE or GREEN or BLUE or WHITE
Your conditional expression if (i == 1) would only trigger on the second iteration of the loop since i will only equal 1 one time.
Try something like:
if (i < (facetResults.length - 1)) {
// only add OR if this isn't the last element of the array
filter = "'" + facetKey + "'" + ":'" + facetResults[i] + " OR";
return filter;
}
Here's your updated code:
Object.keys(facets).forEach(function(facetKey) {
if (facets[facetKey].length > 1) {
facetResults = facets[facetKey];
for (var i = 0; i < facetResults.length; i ++) {
if (i < (facetResults.length - 1)) {
filter = "'" + facetKey + "'" + ":'" + facetResults[i] + " OR";
return filter;
} else {
filter = "'" + facetKey + "'" + ":'" + facetResults[i];
}
}
} else {
filter = "'" + facetKey + "'" + ": " + facets[facetKey] + "'";
return filter;
}
});

Looping through a split array and outputting with wrapInner

I am having difficulty figuring out the best method of doing the following. I am getting anywhere from 0 to x number of string names, ie: Zillow, Trulia. What I am wanting to do is associate an image with those string names and then display them into a list. I am attempting to do a switch statement, but am unsure if that will work for more than 1 condition...please correct me if I am wrong.
So for instance, the variable list is holding two items (Zillow/Trulia), how can I check ky split function variable for multiple values and then add the output: $('#review-icon-list').wrapInner('<li class="review-icon">' + zillowImg + '</li>');
Right now my switch case is throwing an unexpected token error, but I do not think I am using the right method anyways. Does anyone know how I would do this? Would I be doing some sort of loop and if so, how would I structure it?
var reviewSiteNames = 'Zillow,Trulia';
reviewSiteNames = reviewSiteNames.split(',');
console.log(reviewSiteNames);
var zillowImg = '<img src="https://s3.amazonaws.com/retain-static/www/zillow.jpg" alt="Zillow">';
var truliaImg = '<img src="https://s3.amazonaws.com/retain-static/www/trulia.png" alt="Trulia">';
if (reviewSiteNames == '') {
$('#no-current-reviewSites').html('No review sites currently added')
}
/*else if (reviewSiteNames) {
$('#review-icon-list').wrapInner('<li class="review-icon"></li>');
}*/
switch (true) {
case (reviewSiteNames.indexOf('Zillow') >= 0):
$('#review-icon-list').wrapInner('<li class="review-icon">' + zillowImg + '</li>');
break;
case (reviewSiteNames.indexOf('Realtor.com') >= 0):
$('#review-icon-list').wrapInner('<li class="review-icon">' + realtorDotComImg + '</li>');
break;
case (reviewSiteNames.indexOf('Trulia') >= 0):
$('#review-icon-list').wrapInner('<li class="review-icon">' + truliaImg + '</li>');
default: return '';
}​;
New method of trying this. The only image that is displaying is the last if statement in the each function.
$.each(reviewSiteNames, function (index, value) {
if (reviewSiteNames.includes('Zillow')) {
$('#review-icon-current').wrapInner('<li class="review-icon">' + zillowImg + '</li>');
}
if (reviewSiteNames.includes('Trulia')) {
$('#review-icon-current').wrapInner('<li class="review-icon">' + truliaImg + '</li>');
}
//return (value !== 'three');
});
Here is how I would write what I understand from your code:
I think you want to check if some specific word are in the reviewSiteNames array to determine how to wrap the #review-icon-list element.
// Site names as a string
var reviewSiteNames = 'Zillow,Trulia';
// Site names as an array
reviewSiteNames = reviewSiteNames.split(',');
//console.log(reviewSiteNames);
// Some images used in li wrappers...
var zillowImg = '<img src="https://s3.amazonaws.com/retain-static/www/zillow.jpg" alt="Zillow">';
var truliaImg = '<img src="https://s3.amazonaws.com/retain-static/www/trulia.png" alt="Trulia">';
// If the array is empty
if (reviewSiteNames.length == 0) {
$('#no-current-reviewSites').html('No review sites currently added')
}
var myHTMLtoInsert = "";
// Check if specific values are in array
if( $.inArray('Zillow', reviewSiteNames) ){
myHTMLtoInsert += '<li class="review-icon">' + zillowImg + '</li>';
}
if( $.inArray('Realtor.com', reviewSiteNames) ){
myHTMLtoInsert += '<li class="review-icon">' + realtorDotComImg + '</li>';
}
if( $.inArray('Trulia',, reviewSiteNames) ){
myHTMLtoInsert += '<li class="review-icon">' + truliaImg + '</li>';
}
$('#review-icon-list').html(myHTMLtoInsert);
// The names:
var names = 'Zillow,Trulia';
names = names.split(',');
// The images mapper: an object that has names as keys and images as values
var images = {
"Zillow": '<img src="https://s3.amazonaws.com/retain-static/www/zillow.jpg" alt="Zillow">',
"Trulia": '<img src="https://s3.amazonaws.com/retain-static/www/trulia.png" alt="Trulia">'
};
// if names is empty: (names == '' won't work because names is no longer a string, it's an array now)
if (names.length === 0) {
$('#no-current-reviewSites').html('No review sites currently added')
}
// if there is names
else {
// loop through all names
names.forEach(function(name) {
// if this name got an image in the images mapper (images[name] !== undefined)
if(images[name]) {
// then do magic stuff with it
$('#review-icon-list').wrapInner('<li class="review-icon">' + images[name] + '</li>');
}
});
}
I hope this is usefull as I'm not quite sure what the goal really is.

Loop inside loop producing wrong result

I'm having trouble producing a script to match an object's value in object array based on an object's value in a separate array, and retrieve a separate value from that object.
I have used standard for-loops and the current iteration in jQuery each.
I have also tried setting the if statement to look for the two values as ==, but it always produces non matches (or -1).
Can anyone steer me in the right direction here?
transfers = [
{Package: "1", Origin_Facility = "a"},
{Package: "2", Origin_Facility = "b"}
];
storeData = [
{fromPackage: "1,6,26"}
]
var storeDataEach = function( sx, sxv ) {
var transfersEach = function( sy, syv ) {
if(storeData[sx].fromPackage.indexOf(transfers[sy].Package) > -1){
var facilityStore = transfers[sx].Origin_Facility;
storeData[sx].origin = facilityStore + " + " + transfers[sy].Package + ' + ' + storeData[sx].fromPackage;
return false;
} else {storeData[sx].origin = 'error' + transfers[sy].Package + " + " + storeData[sx].fromPackage;return false;}
};
jQuery.each(transfers, transfersEach);
}
jQuery.each(storeData, storeDataEach);
The main problem is you are returning false from the $.each loop which will stop the iteration
A crude fix is to remove the return from else block
var storeDataEach = function(sx, sxv) {
var transfersEach = function(sy, syv) {
if (storeData[sx].fromPackage.indexOf(transfers[sy].Package) > -1) {
var facilityStore = transfers[sx].Origin_Facility;
storeData[sx].origin = facilityStore + " + " + transfers[sy].Package + ' + ' + storeData[sx].fromPackage;
return false;
} else {
storeData[sx].origin = 'error' + transfers[sy].Package + " + " + storeData[sx].fromPackage;
}
};
jQuery.each(transfers, transfersEach);
}
But this still have problems with the data structure, in your example you have 26 in the fromPackage, now if you have a package value of 2 that also will return a positive result

Adding new line after bracket

I am proxying the function console.log to add some information to my logs and I am as well checking whether the information being logged is an object. I do this to avoid getting a log entry of the sort
2016-12-17 (22:12:51) > [object Object]
Code works fine when passing arguments that are not objects. For example, the command
console.log("hello","world");
prints
2016-12-17 (22:23:53) > hello
2016-12-17 (22:23:53) > world
But if I pass an object as well, the code will fail to insert a new line after the object. For example, the command
console.log("hello",{world:true,hello:{amount:1,text:"hello"}},"world");
prints
2016-12-17 (22:27:32) > hello
2016-12-17 (22:27:32) > { world: true, hello: { amount: 1, text: hello } } 2016-12-17 (22:27:33) > world
(note the missing line break after displaying the object).
Code
JQuery 3.1.1
main.js:
(function (proxied) {
function displayArg(argument){
var result= "";
if(typeof argument == "object") {
result += "{ ";
for (i in argument) {
result += i + ": ";
result += (displayArg(argument[i]));
result += ", "
}
result = result.substring(0,result.length - 2);
result += " }";
return result;
} else {
return argument;
}
}
console.log = function () {
var result = [];
for (i in arguments) {
var d = new Date();
result[i] = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate() +
" (" + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + ") > ";
result[i] += displayArg(arguments[i]);
result[i] += "\n";
}
return proxied.apply(this, result);
}
})(console.log);
I'm not fully understanding objective but what about something along the lines of the following oversimplified override:
var oldLog = console.log;
console.log= function(){
var d= new Date(),
dateString = // process string
.....
for(var i = 0; i<arguments.length; i++){
oldLog(dateString, arguments[i]);
}
}
TL;DR change the iterator variables so they don't share name, or add a "var" to the loop definition to make sure they don't escape your desired scope.
It turns out that the for loops from (my own) console.log and displayArg were "sharing" the value of the iterator i. This is because by not declaring the iterator variable, the scope was broader than what I needed. To clarify, look at this example:
console.log({isThis:"real life"},"hello","world")
The code from console.log will add a date to the beginning of result[0] and then call displayArg(arguments[0]), arguments[0] being {isThis:"real life"}. That function, will iterate over the objects properties, thus i will be assigned the value isThis. After the function returns, the value of i will not go back to 0. Instead, i will be isThis and as a consequence, the line
result[i] += "\n";
translates to
result[isThis] += "\n"
instead of
result[0] += "\n"
Probably the most sensible solution was to add a var in the for declaration of the iterators. The following code works as expected:
(function (proxied) {
function displayArg(argument){
var result= "";
if(typeof argument == "object") {
result += "{ ";
for (var i in argument) {
result += i + ": ";
result += (displayArg(argument[i]));
result += ", "
}
result = result.substring(0,result.length - 2);
result += " }";
return result;
} else {
return argument;
}
}
console.log = function () {
var result = [];
for (var i in arguments) {
var d = new Date();
result[i] = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate() +
" (" + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + ") > ";
result[i] += displayArg(arguments[i]);
result[i] += "\n";
}
return proxied.apply(this, result);
}
})(console.log);

Give condition from value that have called

Hello i'd like to put condition for my code in javascript if the code has already called, so after the _edg.source it wont to called again:
for (var j in GexfJS.graph.edgeList) {
var _edg = GexfJS.graph.edgeList[j]
if ( (_edg.target == _curra) && (_edg.source != _nodeIndex) && (_edg.target != _n)) {
var _nod = GexfJS.graph.nodeList[_edg.source];
if(_n != _nod){
_str += '<li><div class="smallpill" style="background: ' + _nod.color.base +'"></div>' + _nod.label + 'b' + ( GexfJS.params.showEdgeWeight && _edg.weight ? ' [' + _edg.weight + ']' : '') + '</li>';
}
}
}
}
try to use condition with an object and set the true value after the value has called, insert this code after the var _nod
check={};
if(check[_nod.label] != true){
......
}
check[_nod.label] = true;

Categories

Resources