Filling an array with objects in Javascript - javascript

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

Related

converting JS array with objects to HTML collection

I got to the point with my project where I decided to simplify some of the js functions where I am looking for a parent in a DOM tree, then drill down to the elements many many times in one function. instead I though I will make instances of a function which will keep some data so then I can refer and operate on objects in easy way. I got it working but as I was going along, I decided to extend functionality and add some extra functions like getElementsByClassNameThenTagName.
I loop through the arrays and if add matching elements to the array.
I have noticed (sadly only now) that I am creating an array with elements rather than HTML collection. As a results, I cannot refer to the objects in my findings by typing buttons['reset'].disabled = false;. I can access my reset button by buttons[3].disabled = false; but this would cause a lot of inconvenience.
I am therefore looking for a way to convert my array with object into a HTML collection.
Please see below my current function:
this.getElementsByClassNameThenTagName = function (elementClass, elementTag) {
if (parentNode == null) {
this.init();
}
var results = [];
var regexStr = elementClass;
var regex = new RegExp(regexStr);
var x = moduleNode.getElementsByClassName(elementClass);
// console.log(x);
var y;
for ( var i = 0; i < x.length; i++ ) {
// console.log(i);
y = x[i].getElementsByTagName(elementTag);
// console.log(y);
for (var k=0; k<y.length; k++){
// console.log(y[k]);
results.push(y[k]);
}
// console.log(results);
}
return results;
};
Any suggestions please?
Thanks.
this.getElementsByClassNameThenTagName = function (elementClass, elementTag) {
if (parentNode == null) {
this.init();
}
var results = {}; // thid should be an object (collection)
var x = moduleNode.querySelectorAll("." + elementClass + " " + elementTag);
x.forEach(function(y) {
var name = y.getAttribute("name"); // if you really sure that all the matched elements have names
results[name] = y;
});
return results;
};
Now you can use the results array like this:
var someElement = results['some name'];
NOTE: All the matched elements x should have a name attribute, and all the name attributes of the matched elements should be unique.

Pushing object to array results in same value

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.

Javascript two dimensional array initialization

Meet with a really weird javascript problem. See my codes below:
function initBadScripts(controlArray) {
var scriptsLine = prompt("Please enter the bad scripts", "debug");
if (scriptsLine != null) {
var pattern = /;/;
var nameList = scriptsLine.split(pattern);
alert(nameList+" "+nameList.length);
for(var counter = 0; counter < nameList.length; counter++){
controlArray[counter][0]=true;
controlArray[counter][1]= new RegExp(nameList[counter],"g");
alert(controlArray[counter][0]);
}
}
alert("wtf!");
}
var controlArray = [[]];
initBadScripts(controlArray);
I defined a function, and call that function. A 2-dimensional array called 'controlArray' is defined with no value. Basically, the function check the user's input and use regular expression to make a 'namelist'. For example, if the user type in
ExampleOne;ExampleTwo
The function will create an array called 'nameList'
nameList=[ExampleOne,ExampleTwo];
Then I want to make a dynamical initialization of the 2-dimensional array called 'controlArray', according to the length of nameList. However this only works fine the nameList'length is 1. If it exceeds one (the user type in 'ExampleOne;ExampleTwo'), the ExampleTwo does not go into the array, and the
alert("wtf");
doesn't run at all. This seems that there is already an error before it. Any comments?
JavaScript doesn't have a true 2-dimensional array. Rather, you're putting a second array inside the first array. Change it to this:
...
for(var counter = 0; counter < nameList.length; counter++){
controlArray[counter] = [true, new RegExp(nameList[counter],"g")];
...
Yes or you declare your variable like that:
var controlArray = [[],[]];
or
var controlArray = new Array(2);
for (var i = 0; i < 2; i++) {
controlArray[i] = new Array(2);
}

Storing and retrieving objects in javascript array();

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
...

How to separate the values from two dimension array in js?

jQuery.get("ChkNewRspLive.php?lastmsgID=" + n, function(newitems){
//some code to separate values of 2d array.
$('#div1').append(msgid);
$('#div2').append(rspid);
});
Let's say the value of newitems is [["320","23"],["310","26"]]
I want to assign "320" and "310" to var msgid.
I want to assign "23" and "26" to var rspid.
How to do that?
I tried to display newitems and the output is "Array". I tried to display newitems[0] and the output is blank.
If I redeclare var newitems = [["320","23"],["310","26"]]; it works. So I guess the variable newitems from jQuery.get is something wrong. Is it I cannot pass the array from other page to current page through jQuery directly?
Regarding the array on other page, if echo json_encode($Arraytest); the output is [["320","23"],["310","26"]] but if echo $Arraytest; the output is Array. How do I pass the array from other page to currently page by jQuery.get?
I don't totally understand the question but I'm going to assume you want the values in an array, as two values can't be stored in one (scalar) variable simultaneously.
jQuery.get("ChkNewRspLive.php?lastmsgID=" + n, function(newitems){
//some code to separate values of 2d array.
var msgid = [],
rspid = [];
for( i = 0 ; i < newitems.length ; i++){
msgid[msgid.length] = newitems[i][0];
rspid[rspid.length] = newitems[i][1];
}
//msgid now contains ["320","310"]
//rspid now contains ["23","26"]
});
Bear in mind those are in the function scope. If you want to use them outside of that scope instantiate them outside. see: closure
You can use pluck from underscore.js: http://documentcloud.github.com/underscore/#pluck
var msgid = _(newitems).pluck(0)
var rspid = _(newitems).pluck(1)
Try this:
function getArrayDimension(arr, dim) {
var res = [];
for(var i = 0; i < arr.length; i++) {
res.push(arr[i][dim]);
}
return res;
}
var newitems = [["320","23"],["310","26"]];
var msgid = getArrayDimension(newitems, 0);
var rspid = getArrayDimension(newitems, 1);
msgid and rspid are arrays holding the 'nth' dimention.
Tnx

Categories