Hi I've searched for the answer but since the tutorials online are all friends = ("bob","fred","joe"); I dont get anywhere. I would like to be able to store several objects with 1-3 values in each index of the array like:
map = [{ground:0},{ground:0, wall:1},{ground:0, item:3}]
The object I have right now looks like:
node = {};
node = {ground:0, object:1};
But when I try the array way I can't access it, all I get "object Object". What would be the correct way to get the values from the map array one by one?
Do you mean:
var map = [{ground:0},{ground:0, wall:1},{ground:0, item:3}];
for(var i = 0; i < map.length; i++) {
console.log(map[i].ground + " item " + map[i].item);
}
Not sure what you want, or what you mean by "the array way", but if you want to get all the values for say ground, then:
var map = [{ground:0},{ground:0, wall:1},{ground:0, item:3}]
for (var i=0, iLen=map.length; i<iLen; i++) {
alert(map[i].ground);
}
Edit
...
alert('item ' + i + ' : ' + map[i].ground); // item 0 : 0
...
Related
I have this array of objects being loaded:
$(document).ready(function () {
$("<div></div>").load("/Stats/Contents #stats", function () {
statcount = $(".list-group-item", this).length;
for (var j = 0; j < statcount; j++) {
statList.push(stat);
}
for (var i = 0; i < statcount; i++) {
statList[i].statId = document.getElementById("statId-" + (i + 1) + "").value;
statList[i].productDescription = document.getElementById("productType-" + (i + 1) + "").value;
statList[i].lastMeasuredInventoryAmount = document.getElementById("statLastMeasureAmount-" + (i + 1) + "").value;
}
)}
)}
.... and so on
Then I get the changed values and save them, however, in the ajax post call, all of the array objects are same (the last one assigned), looks like they get overwritten.
Any ideas? I saw these deferred/promise type code but not sure if there's simpler way.
Thanks.
It sounds like you take the statList array and then push that up to the server, with any respective change. Rather than building and maintaining a list like this, have you thought of switching it around and just grabbing the results out of the markup and building up the array at save point?
$("btnSave").on("click", function(e) {
var data = [];
$(".list-group-item").each(function() {
data.push({
statId: $(this).find(".statid").val(),
.
.
})
});
You wouldn't need to give every element an ID (but could) as my sample uses CSS classes to find the element within the current list item. Additionally, if these are inputs, you could serialize them from the root element more efficiently...
I have the following javascript code that does not work as I would expect it to. I have a list of checkboxes of which two of the items are "TestDuration" and "AssessmentScores". I'm trying to iterate through the list (which works fine) and have it add the values that are checked to the array.
var SAIndex = 0;
var SSIndex = 0;
var ScoresIndex = 0;
var SubAssessments = [];
var SubAssessmentScores = [];
//Get to the container element
var SSList = document.getElementById("islSubAssessmentScore_container");
//turn it into an array of the checkbox inputs
SSList = SSList.getElementsByTagName("input");
//create a temporary object to store my values
var tempPair = new Object();
//iterate through the checkbox lists
for(var i = 1; i < SSList.length;i++)
{
//if the value is checked add it to the array
if (SSList[i].checked)
{
var P = SubAssessments[SAIndex];
var V = SSList[i].value;
//tempPair.Parent = SubAssessments[SAIndex];
tempPair.Parent = P;
//tempPair.Value = SSList[i].value;
tempPair.Value = V;
//show me the values as they exist on the page
alert(tempPair.Parent + "|" + tempPair.Value);
SubAssessmentScores.push(tempPair);
//show me the values I just added to the array
alert(SubAssessmentScores.length-1 + "|" + SubAssessmentScores[SubAssessmentScores.length-1].Parent + "|" + SubAssessmentScores[SubAssessmentScores.length-1].Value);
//uncheck the values so when I refresh that section of the page the list is empty
SSList[i].checked = false;
}
}
//output the list of objects I just created
for (i = 0;i < SubAssessmentScores.length;i++)
alert(i + "|" + SubAssessmentScores[i].Parent + "|" + SubAssessmentScores[i].Value)
Now what happens is that when I iterate through the list I get the following alerts:
-first pass-
StudentID|TestDuration
0|StudentID|TestDuration
-second pass-
StudentID|AssessmentScores
1|StudentID|AssessmentScores
This is what I expect to output... However at the end of the code snippet when it runs the for loops to spit out all the values I get the following alerts...
0|StudentID|AssessmentScores
1|StudentID|AssessmentScores
I can't for the life of me figure out why it's replacing the first value with the second value. I thought it might be using a reference variable which is why I added in the P and V variables to try to get around that if that was the case, but the results are the same.
This is because you are adding the same variable every iteration of the loop.
Try changing your push like this:
SubAssessmentScores.push({
Parent: P,
Value: V
});
That said, I recommend you study a little more javascript and conventions in the language, for example your variable naming is frowned upon because you should only use capital letters on the beginning of a name for constructor functions.
A good book is Javascript the good parts by Douglas Crockford.
I have two fields I need to pull data from in SQL and put that into an array or list that I can loop through. Then for each loop, I do something based on both the fields for each index. What is the best method for this? I thought maybe a dictionary or possibly creating an object?
Right now I pull the fields into two seperate arrays, and I loop through both at the same time, but I am finding that sometimes one array has a blank value, and then they get out of sync and I have issues. This seems like a terrible implementation anyway.
How can I put these into a key value pair and then act on the data?
Edit: I should note that my SQL code just returns a bunch of comma seperated values. So it was easy to create an array out of those, but its proving more difficult to create anything else such as an object because I get all the values at one time.. :(
var equipIDArray = //SQL Gathering code here
var equipTypeArray = //SQL gathering code here
for(var cnt = 0; cnt < equipIDArray.length; cnt++){
alert(cnt);
if(isNaN(equipIDArray[cnt]) === true){
equipIDArray[cnt] = '';
}
switch(equipTypeArray[cnt]){
case 'Blower' :
alert('test1');
break;
case 'Dehumidifier' :
alert('test2');
break;
default :
alert('default');
}
}
It' easy to translate your arrays into an object if they just represent key/value pairs. Then you have an object you can use like a dictionary:
var equipIDArray = ["Blower","Humidifier","Lawn Mower"];
var equipTypeArray = ["Leaf blower","Whole House Humidifier","Honda Brand"];
var equipment = {};
for(var i = 0; i < equipIDArray.length; i++) {
equipment[equipIDArray[i]] = equipTypeArray[i];
}
for(property in equipment) {
console.log(property + " : " + equipment[property]);
alert(property + " : " + equipment[property]);
}
Currently I have an issue with filling an array which I call input in my code with the object which I call athlete in my code.The object which is called athlete is instantiated using several other arrays. I have attached a jsfiddle link to this post which is basically a simplified version with the same issue. I know the logic might look redundant but that is because it is necessary for this example(the actual logic will work with user input).
My issue is that I am filling an array with new Athlete objects, yet I cannot access a specific property of an object in the array.
I am new to working with objects so I'd appreciate any advice on how to make this work. I have added a last line of code to display my input array.
var input = new Array();
var girl=[1,1,1,1];
var boy = [1,1,1,1];
var balleyscore = [100,400,320,50];
var boyHeight = [72,68,65,75];
var girlHeight=[60,57,65,55];
var boyAge = [19,32,22,25];
var girlAge = [20,15,32,18];
//the above are all generate from user inputs
// they go into the object constructor below
function athlete(girl, boy,balleyscore, height, age){
this.girl=girl;
this.boy=boy;
this.balleyscore=balleyscore;
this.height=height;
this.age = age;
};
function insertToObjectArray()
{
var j=0;
var i=0; //insert all our data into one array of the load object
for(j = 0; j < girl.length;j++)
{
input[j]= new athlete(true,false,balleyscore[j],girlHeight[j],girlAge[j]);
}
for(j = girl.length; j <=girl.length+boy.length;j++)
{
input[j]= new athlete(false,true,0,boyHeight[i],boyAge[i]);
i++;
}
};
insertToObjectArray();
document.getElementById("demo").innerHTML=input;
http://jsfiddle.net/qC5j4/1/
To access a property of an object in your array input:
input[0].age
this will allow you to access the first athlete's age
can also be accessed like so:
input[0]['age']
Either way they will both display 20 as the age of the first athlete in the array.
Check it out by console.log(input) in the debugger and then you can play with the data structure.
Ex:
document.getElementById("demo").innerHTML=input[0].age;
Not really sure of your problem, here I have updated your fiddle to display the height property of your athletes by adding the line
output[j]= input[j].height
fiddle
Your athlete object should be for example:
function athlete(age)
{
this.age = age;
}
var item = new athlete(10);
item.age;//10
You can show the height and age like this:
var output = "";
for(var i = 0, length = input.length; i !== length; i++) {
output += "height: "+input[i].height + ", age: " + input[i].age + "<br />";
}
document.getElementById("demo").innerHTML=output;
And there is a little mistake. Use
j < girl.length+boy.length
instead of
j <=girl.length+boy.length
You can access your objects by array index and property name. Change this line document.getElementById("demo").innerHTML=input to this code (list all objects sex and balleyscore in ul#demo):
for (var i=0; i<input.length; i++) {
var node = document.createElement('li'),
txt = document.createTextNode(
(input[i].girl? 'girl' : 'boy') + ' ' + input[i].balleyscore);
node.appendChild(txt);
document.getElementById("demo").appendChild(node);
}
html:
<p><ul id="demo"></ul></p>
FIDDLE
Browser console is very useful for debugging purposes. Try to add this line after objects creation and inspect your array in console:
insertToObjectArray();
console.log(input); // output input array to console
This is trivial I know but I'm so used to OOP languages. I'm trying to figure out how to write out each name/value in either one alert or many, just so I can verify the data
var dCookieNameValuePairs = {};
for (i = 0; i < cookieValues.length; i++)
{
var akeyValuePair = aCookieValues[i].split("=");
dCookieNameValuePairs[keyValuePair[0]] = keyValuePair[1];
}
// display each name value pair testing
for (i = 0; i < dCookieNameValuePairs.length; i++)
{
alert("Name: " + dCookieNameValuePairs[] + "Value: " +
}
I'm stuck at the second for loop...I am not sure how to iterate through the dictionary and then focus on each name/value to spit it back.
You want to use for..in for enumerating through a dictionary/map.
for ( var prop in dCookieNameValuePairs ) {
if ( dCookieNameValuePairs.hasOwnProperty( prop ) ) {
alert( dCookieNameValuePairs[prop] )
}
}
I may have typo'd. Only use .length when you are dealing with an array [] or a custom array-like object that you defined to have .length populated.
for (i in dCookieNameValuePairs) {
alert("Name: " + i + " Value: " + dCookieValuePairs[i]);
}
See the "JavaScript Does Not Support Associative Arrays" section of this page for more details.
If you don't need an associative array, you might put the keys and values into an array of objects instead. So your first loop would look something like this:
for (i = 0; i < cookieValues.length; i++) {
var akeyValuePair = cookieValues[i].split("=");
dCookieNameValuePairs.push({key: akeyValuePair[0], value: akeyValuePair[1]});
}