Object Not Maintaining Assigned Values - javascript

I am looping through an array to create another array of objects in a modified format.
for (i = 1; i <= 37; i++) { // create 37 boxes for days of the month and nearby dates
room_reservations[i] = {};
var this_date = getDate();
var res_count = 0;
for (var res_index = 0; res_index < reservations.length; res_index++) {
var this_res = reservations[res_index];
// bad assignment location
// res_room = JSON.parse(JSON.stringify(this_res));
if (this_res.checkin <= this_date && this_res.checkout > this_date) {
for (var k = 0; k < this_res.rooms.length; k++) {
var res_room = {};
res_room = JSON.parse(JSON.stringify(this_res));
var this_room = res_room.rooms[k];
res_room.room_index = k;
var traveler_count = this_room.travelers.length;
console.log('traveler_count: ', traveler_count);
res_room.traveler_count = traveler_count;
//traveler_counts[i][res_room.room_name] = traveler_count;
console.log('res_room.traveler_count: ', res_room.traveler_count);
var room_name = this_room.room_name;
console.log('room_name: ', room_name);
res_room.room_name = room_name;
console.log('res_room: ', res_room);
room_reservations[i][res_room.room_name] = res_room;
}
}
}
}
Essentially, I console log the object property traveler_count and get the correct value. But when logging the entire object, the property value is incorrect. It's like it grabs the value from the next loop.
How do I fix this? It is not just the logging. The values being set are wrong in the room_reservations array. For example, I set the attribute name to res_room.room_name and the value to res_room. But the attribute name does not match the value in the object.
Please help. Thx

The problem is that you're using the same res_room object every time through the for (var k) loop. So all the properties in res_room[i] are referring to the same object, which you modify in place. You need to make a copy of the object when you assign it.
room_reservations[i][res_room.room_name] = JSON.parse(JSON.stringify(res_room));

Related

undefined parameter in js

I am receiving a type error stating that the array testA[i] is undefined whenever I add an input into the html page. I have the array set and i'm trying to add the value of currency to the array using the push method to add to the second part of the array i.e([0][currency])
function Test() {
var testA = [];
for (i = 0; i < 4; i++) {
this.currency = prompt("Please enter a 3-letter currency abbreviation", "");
testA[i].push(currency);
}
}
var index = new Test();
any help as to why the array is undefined would be appreciated.
Note: I have now tried both testA.push(currency) and testA[i] = this.currency, and I still get the same error as before.
Note: the final version should have it loop through 4 different questions asked and each time adding these into an array. At the end of the loop a new variant of the array should be made and the new set of data entered will be added to it. something like
for(i = 0; i < 4; i++) {
testA[i] = i;
for(j = 0; j < 4; j++) {
this.currency = prompt("Please enter a 3-letter currency abbreviation", "");
testA[i][j] = this.currency;
}
}
but at this point in time I'm just trying to get it to work.
You don't use the push method on a index. You use it on the array itself.
Replace this
testA[i].push(currency);
With this
testA.push(currency);
You need to perform push operation on the array directly.
testA.push(currency);
By executing testA[index] you will receive hold value. In JS it will always return undefined, if index is greater than array length.
Because your array is empty as the beginning, you are always receiving undefined.
You are mixing up two different implementation.
Either you use direct assignation.
var testA = new Array(4);
for (i = 0; i < 4; i += 1) {
this.currency = prompt('...', '');
testA[i] = this.currency;
}
Either you push new values into the array.
var testA = [];
for (i = 0; i < 4; i += 1) {
this.currency = prompt('...', '');
testA.push(this.currency);
}
You should use the second one, which is the most simple soluce.
testA[i] = this.currency OR testA.push(this.currency)
Use Modified function below
function Test() {
var testA = [];
for (i = 0; i < 4; i++) {
this.currency = prompt("Please enter a 3-letter currency abbreviation", "");
testA[i] = this.currency; // use this.currency here if you
}
console.log(testA);
}
var index = new Test();

Infinite for Loop while iterating over an object

I am attempting to store data from an object with arrays into another object with arrays. The data has been stored in the object from a CSV. In this situation the data will start at index 8 and then 19 and 30 and so on and so on. I increment I by 11 to account for this. Not sure why I'm hitting this infinite loop but it's got me quite stuck.
for (var key in states){
var tempDefault = 0;
var tempTotalLoans = 0;
if (states.hasOwnProperty(key)){
//Get Total Defaults and Loans
for (var i = defaultIndex; i < states[key].length; i + 11) {
if (states[key][i] != null && states[key][i] != '') {
tempDefault = parseInt(states[key][i]);
};
};
var defaults = tempDefault;
var totalLoans = tempTotalLoans;
var percent = (defaults/totalLoans)*100;
defaultsObject[key].push(Math.round(percent));
defaultsObject[key].push(totalLoans);
defaultsObject[key].push(defaults);
loadMap();
}
}
Your i + 11 just creates a new value that isn't assigned to anything. You're looking for i += 11. – krillgar

Iterating through Array of Objects to fill input fields

I am currently working on a workaround for Google Forms which will be able to store all inputs in cookies so a user can proceed the survey at a different time.
At the moment I am able to store all questions (a Question is a object that contains: id of the surrounding div, required, userinput in a cookie by using JSON.stringify(). I am also able to read and parse the cookie which gets me an array of all question objects.
Now I want to fill all fields or check all radio buttons which have a value.
My problem is, that the inner for loop does only 2 iterations but it should do 18. Do you have any idea what could be wrong?
function restoreInputs() {
// number of stored cookies
var countCookies = 27;
console.log(countCookies);
// iterate through all cookies
for (var i = 1; i < countCookies + 1; i++) {
var cookiename = "answer" + i;
// get content of cookie (is array of objects)
var answer = checkCookie(cookiename);
// iterate through content
for (var j = 0; j < answer.length; j++) {
// get value of object
var val = answer[j].value;
// get the input field (textarea or radio button)
var x = document.getElementById(answer[j].n).getElementsByTagName('input');
// if input is radio, then check the one at position stored in value of object
if (x[j].type === "radio") {
x[val].checked = true;
// if textarea set its value to the one stored in object value
} else {
x[j].value = val;
}
console.log("j: " + j);
}
}
console.log(i);
}
I found the solution. The problem was that I forgot a for loop, since var x = document.getElementById(answer[j].n).getElementsByTagName('input'); may return more than one element. So here is the solution:
function restoreInputs() {
// number of stored cookies
var countCookies = 27;
console.log(countCookies);
// iterate through all cookies
for (var i = 1; i < countCookies + 1; i++) {
var cookiename = "answer" + i;
// get content of cookie (is array of objects)
var answer = checkCookie(cookiename);
// iterate through content
for (var j = 0; j < answer.length; j++) {
// get value of object
var val = answer[j].value;
// get the input field (textarea or radio button)
var x = document.getElementById(answer[j].n).getElementsByTagName('input');
// if input is radio, then check the one at position stored in value of object
for (var k = 0; k < x.length; k++) {
if (x[k].type === "radio") {
x[val].checked = true;
// if textarea set its value to the one stored in object value
} else {
x[k].value = val;
}
}
console.log("j: " + j);
}
}
console.log(i);
}

Multidimensional array showing duplicate values

I'm adding values to a multidimensional array using loops
var leg_array = {};
var enc_array = [];
for (var c = 0; c < result.routes[0].legs.length; c++) {
leg_array[c] = {};
for (var b = 0; b < result.routes[0].legs[c].steps.length; b++) {
//var lat_lngs = result.routes[0].legs[c].steps[b].encoded_lat_lngs; //encoded polyline representation
var start_location_A = result.routes[0].legs[c].steps[b].start_location.A;
var start_location_F = result.routes[0].legs[c].steps[b].start_location.F;
var end_location_A = result.routes[0].legs[c].steps[b].end_location.A;
var end_location_F = result.routes[0].legs[c].steps[b].end_location.F;
enc_array[b] = start_location_A + "," + start_location_F + ":" + end_location_A + "," + end_location_F;
leg_array[c] = enc_array;
}
}
console.log(leg_array);
When i check the console log, the arrays in the first level of the multi dimensional array are identical.
How can i solve this? Values of enc_array are duplicate in every leg_array
e.g. leg_array[0] = enc_array, leg_array[1] = enc_array
enc_array is the same when the values should be different.
You are referencing the same array multiple times. If you want to create different arrays for each leg_array[c] value, use the Array.prototype.slice method instead:
leg_array[c] = enc_array.slice()
This will create a new copy of enc_array (in it's current form) to store in leg_array[c].
Of course, if you do that in the current location, it will set that same value multiple times (because it's inside the loop). Moving it to be inside the outer for loop will probably get the result you want.

Netsuite Javascript Grab Last Array Value

So I found some info on this site on how to go about grabbing the value of the last index of an array. I have an Array that is of an unknown length. It builds based on a search of results. For example:
var custid = nlapiGetFieldValue('entity');
var custRecord = nlapiLoadRecord('customer', custid);
var itemPriceLineCount = custRecord.getLineItemCount('itempricing');
for (var i = 1; i <= itemPriceLineCount; i++) {
var priceItemId = [];
priceItemId = custRecord.getLineItemValue('itempricing', 'item', i);
if (priceItemId == itemId) {
var histCol = [];
histCol[0] = new nlobjSearchColumn('entity');
histCol[1] = new nlobjSearchColumn('totalcostestimate');
histCol[2] = new nlobjSearchColumn('tranid');
histCol[3] = new nlobjSearchColumn('trandate');
var histFilter = [];
histFilter[0] = new nlobjSearchFilter('entity', null, 'is', custid);
histFilter[1] = new nlobjSearchFilter('item', null, 'is', itemId);
var histSearch = nlapiSearchRecord('invoice', null, histFilter, histCol);
for (var h = 0; h <= histSearch.length; h++) {
var itemRate = new Array();
var histSearchResult = histSearch[h];
itemRate = histSearchResult.getValue('totalcostestimate');
}
}
}
Now when I use:
var last_element = itemRate[itemRate.length - 1];
It gives me the number of digits/placeholders in each element of the array. So as per my example I know my array holds the values of .00 and 31.24 because I put them there for a test. So last_element will result in 3 and 5. How can I grab the value 31.24 or the last element period? I need the value not the number of digits.
var itemRate = new Array();// Not sure what you intend to do with this array
var histSearchResult = histSearch[h];
itemRate = histSearchResult.getValue('totalcostestimate'); // but note `itemRate` is no more an array here. Its a variable having the value of `totalcostestimate` in string format
Now coming to your use case
/* you're trying to get the length of the string value and subtracting -1 from it.
So its very obvious to get those number of digits */
var last_element = itemRate[itemRate.length - 1]; // returns you that index value of the string
If you want to get the last array value of your search i.e histSearch
You may want to do something like this
var last_element = histSearch[histSearch.length-1].getValue('totalcostestimate');
As a side note it is always recommended to validate the returning value from a saved search result. Because on a successful search it returns you an array object on the other hand if no result founds it'll return you null.
//likely to get an error saying can't find length from null
for (var h = 0; h <= histSearch.length; h++) {
}
You can use something like this
// Never enter into the loop if it is null
for (var h = 0; histSearch!=null && h <= histSearch.length; h++) {
}

Categories

Resources