Javascript: loop through array - javascript

This is driving me crazy. I'm just trying to print out an array and it's not working. What am I missing? The results variable is returning "undefined" which much mean my for loop isn't working correctly. Everything else works properly, the console.log I have correctly displays the fields are added to the array.
// The list of accounts array.
var accountsArray = [];
function addAccount() {
// Take fields and put user data into varables.
var accountName = document.getElementById('accountName').value;
var accountBalance = document.getElementById('accountBalance').value;
var accountType = document.getElementById("accountType");
var accountTypeSelected = accountType.options[accountType.selectedIndex].text;
var accountCurrency = document.getElementById("accountCurrency");
var accountCurrencySelected = accountCurrency.options[accountCurrency.selectedIndex].text;
// Put these variables into the array.
accountsArray.push(accountName);
accountsArray.push(accountBalance);
accountsArray.push(accountTypeSelected);
accountsArray.push(accountCurrencySelected);
// Items added to the array, logged.
console.log('user added: ' + accountsArray);
}
function accountsListHtml() {
var results;
// Loop through the array
for (var i = 0; i < accountsArray.length; i++) {
results = accountsArray[i];
}
document.getElementById('accountsList').innerHTML = results;
}
Here's a link to all the files. It's an iOS web app using Framework7. Balance Pro

You are calling accountsListHtml() in body.onload. At that point accountsArray is empty.
I can't find any other possibility to call accountsListHtml() on that page you linked to.
Add one line inside function addAccount() and it will work:
function addAccount() {
/* vour code */
console.log('user added: ' + accountsArray);
accountsListHtml(); // add this line
}

Try changing results = accountsArray[i]; to results += accountsArray[i];.
Update
And initialize results with an empty string, for example :)

for (var i = 0; i < accountsArray.length; i++) {
results = accountsArray[i];
}
The statement in the for loop i.e. results = accountsArray[i]; overwrites the variable results evry loop run. You could change the statement to :
results += accountsArray[i].toString();
and initialise results to an empty string.

The following works for me: http://jsfiddle.net/95ztrmk3/13/
HTML:
<div id="accountsList"></div>
JS:
// The list of accounts array.
var accountsArray = [];
addAccount();
accountsListHtml();
function addAccount() {
// Take fields and put user data into varables.
var accountName = "John Doe";
var accountBalance = "500.00";
var accountTypeSelected = "Checking"
var accountCurrencySelected = "USD";
// Put these variables into the array.
accountsArray.push(accountName);
accountsArray.push(accountBalance);
accountsArray.push(accountTypeSelected);
accountsArray.push(accountCurrencySelected);
// Items added to the array, logged.
console.log('user added: ' + accountsArray);
}
function accountsListHtml() {
var results = [];
// Loop through the array
for (var i = 0; i < accountsArray.length; i++) {
results += accountsArray[i] + " ";
}
document.getElementById('accountsList').innerHTML = results;
console.log(results);
}
Assuming the input isn't malformed or otherwise weird. I made sure Javascript recognizes results is an empty array and not a string or something: var results = []

Related

how do I check if a value is in a JSON return or not?

I'm writing a test in postman where I want to check if a JSON return contains the Label called 'RegressieMapTest'. This is my script:
pm.test("Is the folder created correctly?", function(){
var jsonData = pm.response.json();
var objString = JSON.stringify(jsonData);
var obj = JSON.parse(objString);
for (var i = 0; i < obj.Corsa.Data.length; i++){
if (obj.Corsa.Data[i].Label == "RegressieMapTest"){
console.log(obj.Corsa.Data[i].Label);
pm.expect(obj.Corsa.Data.Label).to.eql("RegressieMapTest");
}
}
pm.expect.fail();
})
But it doesn't quite work, every time I run this script it seems like it automatically jumps to pm.expect.fail() which is weird because 'RegressieMapTest' is inside the JSON return. Postman returns the following message:
Is the folder created correctly? | AssertionError: expect.fail()
pm.respose.json() is equalent to JSON.parse you don't have to do it again
also you can use array.find method instead of looping through it
pm.test("Is the folder created correctly?", function () {
var jsonData = pm.response.json();
pm.expect(obj.Corsa.Data.find(elem => elem.Label === "RegressieMapTest")).to.be.not.undefined
}
if array has any element with label RegressieMapTest then it will return that data elese returns undefined, so we are validating that it will not return undefined. Meaning it has the value
Your pm.expect.fail(); always runs. You want it to run only when you don't find the field. So just add a flag in your check block.
pm.test("Is the folder created correctly?", function(){
var jsonData = pm.response.json();
var objString = JSON.stringify(jsonData);
var obj = JSON.parse(objString);
var isFound = false;
for (var i = 0; i < obj.Corsa.Data.length; i++){
if (obj.Corsa.Data[i].Label == "RegressieMapTest"){
console.log(obj.Corsa.Data[i].Label);
pm.expect(obj.Corsa.Data.Label).to.eql("RegressieMapTest");
isFound = true;
}
}
if (!isFound) {
pm.expect.fail();
}
})

JavaScript - Issues recovering a map in an object after being saved in localStorage

I've been dealing with this for some time. I've a list of sections in which the user checks some checkboxes and that is sent to the server via AJAX. However, since the user can return to previous sections, I'm using some objects of mine to store some things the user has done (if he/she already finished working in that section, which checkboxes checked, etc). I'm doing this to not overload the database and only send new requests to store information if the user effectively changes a previous checkbox, not if he just starts clicking "Save" randomly. I'm using objects to see the sections of the page, and storing the previous state of the checkboxes in a Map. Here's my "supervisor":
function Supervisor(id) {
this.id = id;
this.verif = null;
this.selections = new Map();
var children = $("#ContentPlaceHolder1_checkboxes_div_" + id).children().length;
for (var i = 0; i < children; i++) {
if (i % 2 == 0) {
var checkbox = $("#ContentPlaceHolder1_checkboxes_div_" + id).children()[i];
var idCheck = checkbox.id.split("_")[2];
this.selections.set(idCheck, false);
}
}
console.log("Length " + this.selections.size);
this.change = false;
}
The console.log gives me the expected output, so I assume my Map is created and initialized correctly. Since the session of the user can expire before he finishes his work, or he can close his browser by accident, I'm storing this object using local storage, so I can change the page accordingly to what he has done should anything happen. Here are my functions:
function setObj(id, supervisor) {
localStorage.setItem(id, JSON.stringify(supervisor));
}
function getObj(key) {
var supervisor = JSON.parse(localStorage.getItem(key));
return supervisor;
}
So, I'm trying to add to the record whenever an user clicks in a checkbox. And this is where the problem happens. Here's the function:
function checkboxClicked(idCbx) {
var idSection = $("#ContentPlaceHolder1_hdnActualField").val();
var supervisor = getObj(idSection);
console.log(typeof (supervisor)); //Returns object, everythings fine
console.log(typeof (supervisor.change)); //Returns boolean
supervisor.change = true;
var idCheck = idCbx.split("_")[2]; //I just want a part of the name
console.log(typeof(supervisor.selections)); //Prints object
console.log("Length " + supervisor.selections.size); //Undefined!
supervisor.selections.set(idCheck, true); //Error! Note: The true is just for testing purposes
setObj(idSection, supervisor);
}
What am I doing wrong? Thanks!
Please look at this example, I removed the jquery id discovery for clarity. You'll need to adapt this to meet your needs but it should get you mostly there.
const mapToJSON = (map) => [...map];
const mapFromJSON = (json) => new Map(json);
function Supervisor(id) {
this.id = id;
this.verif = null;
this.selections = new Map();
this.change = false;
this.selections.set('blah', 'hello');
}
Supervisor.from = function (data) {
const id = data.id;
const supervisor = new Supervisor(id);
supervisor.verif = data.verif;
supervisor.selections = new Map(data.selections);
return supervisor;
};
Supervisor.prototype.toJSON = function() {
return {
id: this.id,
verif: this.verif,
selections: mapToJSON(this.selections)
}
}
const expected = new Supervisor(1);
console.log(expected);
const json = JSON.stringify(expected);
const actual = Supervisor.from(JSON.parse(json));
console.log(actual);
If you cant use the spread operation in 'mapToJSON' you could loop and push.
const mapToJSON = (map) => {
const result = [];
for (let entry of map.entries()) {
result.push(entry);
}
return result;
}
Really the only thing id change is have the constructor do less, just accept values, assign with minimal fiddling, and have a factory query the dom and populate the constructor with values. Maybe something like fromDOM() or something. This will make Supervisor more flexible and easier to test.
function Supervisor(options) {
this.id = options.id;
this.verif = null;
this.selections = options.selections || new Map();
this.change = false;
}
Supervisor.fromDOM = function(id) {
const selections = new Map();
const children = $("#ContentPlaceHolder1_checkboxes_div_" + id).children();
for (var i = 0; i < children.length; i++) {
if (i % 2 == 0) {
var checkbox = children[i];
var idCheck = checkbox.id.split("_")[2];
selections.set(idCheck, false);
}
}
return new Supervisor({ id: id, selections: selections });
};
console.log(Supervisor.fromDOM(2));
You can keep going and have another method that tries to parse a Supervisor from localStorageand default to the dom based factory if the localStorage one returns null.

firebase - javascript object returning undefined

I have a firebase set up. here is the structure:
I am having trouble getting the 'newNroomID' value (that is a6QVH, a7LTN etc..).
this value will be use to compare with the other variable value.
I know that in javascript, to access the value of the object it can be done like this:
var card = { king : 'spade', jack: 'diamond', queen: 'heart' }
card.jack = 'diamond'
but it seems different story when it comes with the firebase or surely enough i am missing something. Here is my code.
var pokerRoomsJoin = firebase.database().ref(); // this is how i set it up this block of code is for reading the data only
pokerRoomsJoin.on('value', function(data){
var rID = data.val();
var keys = Object.keys(rID);
var callSet = false;
for (var i = 0 ; i < keys.length; i++) {
var indexOfKeys = keys[i];
var roomMatching = rID[indexOfKeys];
var matchID = roomMatching.newNroomID; // this does not work alwaus give me undefined
console.log('this return :' + matchID + ' WHY!')
console.log(roomMatching)
if(matchID == 'ffe12'){ // 'ffe12' is actually a dynamic value from a paramiter
callSet = true;
}
}
})
and here is the result of the console log:
strangely i am able to access it like this
var matchID = roomMatching.newNroomID // it return a6QVH and a7LTN one at a time inside the loop
only if i set up the ref to :
var pokerRoomsJoin = firebase.database().ref('room-' + roomId);
I've tried searching but seems different from the structure i have . am I having bad data structure? Save me from this misery , thanks in advance!
Let us see the code inside for loop line by line,
1. var indexOfKeys = keys[i];
now indexOfKeys will hold the key room-id
2. var roomMatching = rID[indexOfKeys];
here roomMatching will hold the object
{ 'firebasePushId': { newDealerName: 'b',
...,
}
}
Now
3. var matchID = roomMatching.newNroomID;
This of-course will be undefined because roomMatching has only one
property , firebasePushId.
To access newNroomID , you have to do something like this,
matchID = roomMatching.firebasePushKey.newNroomID .
One way to get firebasePushKeys will be using Object.keys(roomMatching).

Javascript Array strange behavior. Global declaration is unable to hold value

I have the following code in one of my function. I have an array 'arr' which is working correctly when used inside if{}. But its now working when using outside it. Can anyone point me what I am missing.
function runQueries()
{
var arr = new Array;
db.transaction (function (transaction)
{
var sql = "SELECT * FROM incomecategory";
transaction.executeSql (sql, undefined,
function (transaction, result)
{
if (result.rows.length)
{
for (var i = 0; i < result.rows.length; i++)
{
var row = result.rows.item (i);
var categoryname = row.categoryname;
arr[i] = categoryname;
}
//alert(arr[0]); // It works
}
else
{
}
}, error);
});
//alert (arr[0]); // It doesn't work.
}
It's asynchronous behavior. Your alert at the bottom of the code is probably executed before the database query.

return from JS function

basic JS question, please go easy on me I'm a newb :)
I pass 2 variables to the findRelatedRecords function which queries other related tables and assembles an Array of Objects, called data. Since findRelatedRecords has so many inner functions, I'm having a hard time getting the data Array out of the function.
As it currently is, I call showWin inside findRelatedRecords, but I'd like to change it so that I can get data Array directly out of findRelatedRecords, and not jump to showWin
function findRelatedRecords(features,evtObj){
//first relationship query to find related branches
var selFeat = features
var featObjId = selFeat[0].attributes.OBJECTID_1
var relatedBranch = new esri.tasks.RelationshipQuery();
relatedBranch.outFields = ["*"];
relatedBranch.relationshipId = 1; //fac -to- Branch
relatedBranch.objectIds = [featObjId];
facSel.queryRelatedFeatures(relatedBranch, function(relatedBranches) {
var branchFound = false;
if(relatedBranches.hasOwnProperty(featObjId) == true){
branchFound = true;
var branchSet = relatedBranches[featObjId]
var cmdBranch = dojo.map(branchSet.features, function(feature){
return feature.attributes;
})
}
//regardless of whether a branch is found or not, we have to run the cmdMain relationship query
//the parent is still fac, no advantage of the parent being branch since cmcMain query has to be run regardless
//fac - branch - cmdMain - cmdSub <--sometimes
//fac - cmdMain - cmdSub <-- sometimes
//second relationship query to find related cmdMains
var relatedQuery = new esri.tasks.RelationshipQuery();
relatedQuery.outFields = ["*"];
relatedQuery.relationshipId = 0; //fac -to- cmdMain
relatedQuery.objectIds = [featObjId];
//rather then listen for "OnSelectionComplete" we are using the queryRelatedFeatures callback function
facSel.queryRelatedFeatures(relatedQuery, function(relatedRecords) {
var data = []
//if any cmdMain records were found, relatedRecords object will have a property = to the OBJECTID of the clicked feature
//i.e. if cmdMain records are found, true will be returned; and continue with finding cmdSub records
if(relatedRecords.hasOwnProperty(featObjId) == true){
var fset = relatedRecords[featObjId]
var cmdMain = dojo.map(fset.features, function(feature) {
return feature.attributes;
})
//we need to fill an array with the objectids of the returned cmdMain records
//the length of this list == total number of mainCmd records returned for the clicked facility
objs = []
for (var k in cmdMain){
var o = cmdMain[k];
objs.push(o.OBJECTID)
}
//third relationship query to find records related to cmdMain (cmdSub)
var subQuery = new esri.tasks.RelationshipQuery();
subQuery.outFields = ["*"];
subQuery.relationshipId = 2;
subQuery.objectIds = [objs]
subTbl.queryRelatedFeatures(subQuery, function (subRecords){
//subRecords is an object where each property is the objectid of a cmdMain record
//if a cmdRecord objectid is present in subRecords property, cmdMain has sub records
//we no longer need these objectids, so we'll remove them and put the array into cmdsub
var cmdSub = []
for (id in subRecords){
dojo.forEach(subRecords[id].features, function(rec){
cmdSub.push(rec.attributes)
})
}
var j = cmdSub.length;
var p;
var sub_key;
var obj;
if (branchFound == true){
var p1 = "branch";
obj1 = {};
obj1[p1] = [cmdBranch[0].Branches]
data.push(obj1)
}
for (var i=0, iLen = cmdMain.length; i<iLen; i++) {
p = cmdMain[i].ASGMT_Name
obj = {};
obj[p] = [];
sub_key = cmdMain[i].sub_key;
for (var j=0, jLen=cmdSub.length; j<jLen; j++) {
if (cmdSub[j].sub_key == sub_key) {
obj[p].push(cmdSub[j].Long_Name);
}
}
data.push(obj);
}
showWin(data,evtObj) <---this would go away
})
}
//no returned cmdRecords; cmdData not available
else{
p = "No Data Available"
obj = {}
obj[p] = []
data.push(obj)
}
showWin(data,evtObj) <--this would go away
})
})
}
I'd like to have access to data array simply by calling
function findRelatedRecords(feature,evt){
//code pasted above
}
function newfunct(){
var newData = findRelatedRecords(feature,evt)
console.log(newData)
}
is this possible?
thanks!
Edit
Little more explanation.....
I'm connecting an Object event Listener to a Function like so:
function b (input){
dojo.connect(obj, "onQueryRelatedFeaturesComplete", getData);
obj.queryRelatedFeatures(input);
console.log(arr) //<----this doesn't work
}
function getData(relatedFeatData){
var arr = [];
//populate arr
return arr;
}
So when obj.QueryRelatedFeatures() is complete, getData fires; this part works fine, but how to I access arr from function b ?
Post Edit Update:
Due to the way that this event is being hooked up you can't simple return data from it. Returning will just let Dojo call to the next method that is hooked up to onSelectionComplete.
When init runs it is long before findRelatedRecords will ever be executed/fired by the onSelectionComplete event of the well, which is why you were seeing undefined/null values. The only way to work with this sort of system is to either 1) call off to a method like you're already doing or 2) fire off a custom event/message (technically it's still just calling off to a method).
If you want to make this method easier to work with you should refactor/extract snippets of it to make it a smaller function but contained in many functions. Also, changing it to have only one exit point at the end of the findRelatedRecords method will help. The function defined inside of subTbl.queryRelatedFeatures() would be a great place to start.
Sorry, you're kind of limited by what Dojo gives you in this case.
Pre Edit Answer:
Just return your data out of it. Everywhere where there is a showWin call just use this return.
return {
data: data,
evtObj: evtObj
}
Then your newfunct would look like this.
function newfunct(){
var newData = findRelatedRecords(feature,evt);
console.log(newData);
console.log(newData.data);
console.log(newData.evtObj);
}
If you only need that "data" object, then change your return to just return data;.
Also, start using semicolons to terminate statements.

Categories

Resources