JavaScript - How To Create Nested Objects Array In Javascript
Hi,
I am a begginer in javascript, please help on below I want to create an object with nested objects array like following: var country{ var states=new array(); } var state { city,pincode } this should be called like var city= country[0].state[0].city; any idea will be appreciated Similar TutorialsHi, Can i sort an array of objects in javascript?. I am having the value as Code: var myVarr = [{"name":"xyz","age":21}, {"name":"cde","age":25}]. The above array has two objects. I need to sort by age using javascript. Please help. Regards, anas Sorry folks, Im not sure that I am using the correct terminology here. What i would like to do is sort an array based on the [SortBy] value, however this array is nested. For instance: ar.[SortBy]"PartNumber" ar.[0].[PartNumber]"123" ar.[0].[PartName]"Widget1" ar.[1].[PartNumber]"345" ar.[1].[PartName]"Widget2" ar.[2].[PartNumber]"456" ar.[2].[PartName]"Widget3" ar.[3].[PartNumber]"567" ar.[3].[PartName]"Widget4" Thanks! I'm trying to reuse some code in a different context to do a different job. The code to be reused contains hundreds of lines similar to a = new b.c.d(e,f) with different value for e and f. I need to create a new user defined object with the structure b.c.d. I've made numerous attempts along the lines of: Code: function d (e, f) { this.e = e; this.f = f; } function c () { this.d = d (e, f); } function b () { this.c = c; } var a = new b.c.d("test", "message"); with various permuations of functional declarations. However I get error message "Object expected" or "b.c.d is null or not an object" at the final line of the example. It works with the test line var a = new d("test", "message") but not when I start to build up the expression. How should I define of b.c.d? Hi, I am having trouble with a recursive function I created to list out the indexes and values of various nested objects. Code: var macros={ CTRL: { ALT: { ENTER: "<br />", P: "<p>.</p>", A: "<a href=\"\">.</a>", _1: "<h1>.</h1>", _2: "<h2>.</h2>", _3: "<h3>.</h3>", _4: "<h4>.</h4>", _5: "<h5>.</h5>", _6: "<h6>.</h6>" } } }; I want to print out the whole 'bread crumb trail' to each object, ie CTRL ALT 6: <h6>.</h6>, but at the moment my function prints out CTRL ALT twice for 'ENTER' and then never again. The function: Code: function printObj(obj) { for(i in obj) { var n=i.replace("_", ""); document.write(n); if(typeof obj[i]=="string") { document.write(":"); document.write(" "+obj[i].replace(/</g, "<").replace(/>/g, ">")); } else { document.write(n); } if(typeof obj[i]=="object") printObj(obj[i]); document.write("\n"); } } printObj(macros); The current output: Code: CTRLCTRLALTALTENTER: <br /> P: <p>.</p> A: <a href="">.</a> 1: <h1>.</h1> 2: <h2>.</h2> 3: <h3>.</h3> 4: <h4>.</h4> 5: <h5>.</h5> 6: <h6>.</h6> Any advice would be appreciated. Cheers, Gus I posted this once, but it disappeared, and I have no notifications that I did anything wrong. I read the rules before posting and wasn't breaking any so I am not sure why it disappeared but here goes again. I am trying to learn Javascript (particularly OOP) from a series of screencasts by Douglas Crockford. I have developed a theoretical "game" to build to illustrate it to myself better, and learn by example. I must be misunderstanding how inheritance works, because my code is not producing the results I thought it would. Here is what I have, followed by an explanation of my understanding. Code: $(function() { function object(o) { function Funct() {} Funct.prototype = o; return new Funct(); } soldier = { pointsCost: 0, movement: "1 Infantry Block", validTargets: {}, weapons: { "Main Weapon": { "Weapon Type": "M4 Carbine", "Fire Range": 12 }, "Secondary Weapon": { "Weapon Type": "JCP .45", "Fire Range": 3 } } }; var rifleman = object(soldier); rifleman.pointsCost += 10; rifleman.validTargets.target1 = "Infantry" rifleman.weapons["Secondary Weapon"]["Weapon Type"] = ""; rifleman.weapons["Secondary Weapon"]["Fire Range"] = ""; var heavyGunner = object(soldier); heavyGunner.pointsCost += 20; heavyGunner.validTargets.target1 = "Infantry"; heavyGunner.validTargets.target2 = "Light Armor"; heavyGunner.weapons["Main Weapon"]["Weapon Type"] = "SAW M249"; heavyGunner.weapons["Main Weapon"]["Fire Range"] = 12; heavyGunner.weapons["Secondary Weapon"]["Weapon Type"] = ""; heavyGunner.weapons["Secondary Weapon"]["Fire Range"] = ""; var sniper = object(soldier); sniper.pointsCost += 30; sniper.validTargets.target1 = "Infantry"; sniper.weapons["Main Weapon"]["Weapon Type"] = "Savage .308"; sniper.weapons["Main Weapon"]["Fire Range"] = 20; sniper.weapons["Secondary Weapon"]["Weapon Type"] = "JCP .45"; sniper.weapons["Secondary Weapon"]["Fire Range"] = 3; var demolitions = object(soldier); demolitions.pointsCost += 30; demolitions.validTargets.target1 = "Infantry"; demolitions.validTargets.target2 = "Light Armor"; demolitions.validTargets.target3 = "Artilery"; demolitions.validTargets.target4 = "Structures"; demolitions.weapons["Main Weapon"]["Weapon Type"] = "SMAW MK153"; demolitions.weapons["Main Weapon"]["Fire Range"] = 16; demolitions.weapons["Secondary Weapon"]["Weapon Type"] = "M1014 Combat Shotgun"; demolitions.weapons["Secondary Weapon"]["Fire Range"] = 1; var infantry = { rifleman: rifleman, heavyGunner: heavyGunner, sniper: sniper, demolitions: demolitions }; console.log(infantry); }); I start by creating an object function that accepts an object passed in, and sets it to the prototype of a constructor (that would allow me to create a new object linked to, and inheriting from, the initial passed in object) I initialized a solider object literal, and pass that into the object function while creating 4 new objects (rifleman, heavyGunner, sniper, demolitions) These four should inherit from and customize upon the soldier object. The way I understood inheritance is that the new objects (example. rifleman) would inherit properties from the old object (i.e. soldier) and change or add properties, affecting only the new (rifleman) object but not changing the old(solider) object. this works ok somewhat in my example, until it comes to nested objects. In the above example I have objects as values for some Object's properties. (i.e. validTargets and weapons) When I change or add these, all of the new objects seem to inherit the last declarations, from demolitions, as if demolitions is actually changing that part of the soldier object so that the other's inherit those properties. From my viewpoint, I expected these values to not be changed and that the 4 infantry types had no link to each other, but only to the soldier object. I apparently misunderstood something, or coded something wrong. Some minor notes: -I will be updating most of the "string" values to be objects, so for instance, the validTargets value of "Infantry" would actually be the infantry object, stating that any of the 4 solider types would be a valid target. - I intend to create weapons as their own viable objects in the future, and pass those objects instead of "strings" - I intend to extend this (once this is working) to create an armor object that contains armor type units, similar in structure to the infantry object. - If I can get this all to work, I may make this into a "simple" dice style battle game. but that is way off, I just want to get this nesting of objects to work with inheritance for now. Thanks in advance for any help you can provide. Here is a link to the "live" example. (not much different there except if you have firebug you can see the console.log method showing the objects, and how they are inheriting in properly from my POV.) Link to Live example... Blue This is a little hard to explain so I'm posting an example. Code: //NESTED FUNCTION I'M USING TO DEMONSTRATE MY QUESTION function foo(a) { this.x = 5; //USED TO SET THE VALUE OF X if( a == 0 ) return function(z) { return x = z; } //USED TO RETRIEVE THE VALUE OF X else if( a == 1 ) return function() { return x; } } //MAKES setX THE SETTER FUNCTION var setX = foo(0); //MAKES getX THE GETTER FUNCTION var getX = foo(1); print( "setX(25), not an instance: " + setX( 25 ) ); print( "getX(), not an instance: " + getX() ); print( "" ); //CREATES AN OBJECT INSTANCE USING FOO AS CONSTRUCTOR var q = new foo(); print( "value of x in object instance: " + q.x ); print( "" ); print( "setX(25), not an instance: " + setX( 25 ) ); print( "getX(), not an instance: " + getX() ); This code will output: Code: setX(25), not an instance: 25 getX(), not an instance: 25 value of x in object instance: 5 setX(25), not an instance: 25 getX(), not an instance: 25 Observations: It seems like this.x actually has two meanings. 1)x becomes a member of the "Function" object foo(). 2)x becomes a part of the constructor for prototype class foo. But why then does x revert back to the original value of 5 when I use foo as a constructor? Does javascript automatically save the original value on creation for a reason? What is going on behind the scenes to make this happen? Is this behavior part of an ontological model that makes sense? Similarly, if I change "this.x" to "var x" I can access the value of x but I can't change it. Not that that I should be able to, the syntax "var x" doesn't make x a member of foo anyway. But I'm still having trouble classifying the relationship "var x" has to the function. Anyways this is more of a tangent. My main question is above but if anyone has something to say about this, I'd be interested to hear it. It seems like all these behaviors have rules to them, but there is no conceptual model to think through that guide these behaviors. Or maybe I'm just ignorant. Enlighten me. I was looking at that old Strawberry Fields problem and I thought I'd see about solving it in JavaScript. What I want is an array of chars so that I can set individual elements in the array of arrays. Strings are apparently immutable and can't directly be changed? Here's my code. Code: var field = new Array(); var string0 = "..@@@@@..............." var string1 = "..@@@@@@........@@@..." var string2 = ".....@@@@@......@@@..." var string3 = ".......@@@@@@@@@@@@..." var string4 = ".........@@@@@........" var string5 = ".........@@@@@........" for (var i = 0; i < 6; i++) { field[i] = new Array(); field[i] = eval("string" + i + ".slice('')"); } document.write("field's type is " + typeof field + "<br>"); // object? but it should be explicit array document.write(typeof field[1]) // string? it should explicitly be an array, then it was filled with array elements document.write(typeof field[1][2]); // string - ok, I understand this bit document.write(field[1].length); document.write("<br>"); for (var i = 0; i < field.length; i++) { field[i] = new Array(); for (var k = 0; k < eval("string" + i + ".length"); k++) { field[i][k] = eval("string" + i + ".charAt(" + k + ")"); } document.write("<br>"); } document.write("field's type is " + typeof field + "<br>"); // seriously, an object? document.write(typeof field[1]) // why is this an object instead of an array? document.write(typeof field[1][2]); // string, yeah, I understand this as well document.write(field[1].length); document.write("<br>"); Also, it looks like I can't overwrite a 1-length string that's in the array of arrays. For instance: Code: newField = field; //for loops newField[i][k] = 0; // does nothing, newField's elements remain the same. Let's say I would want to create a custom object with properties. The properties would get their values from text input fields. The only thing that I can't get is how to assign variables to the new instances of the object.Here's my go at it: //First create object prototype function Obj(prop1,prop2,prop3) { this.prop1=prop1; this.prop2=prop2; this.prop3=prop3; this.showProps=showProps; //This method will show all props } //Array for storing each object instance var Objects=new Array(),i=-1; //---Now the HTML code <form name="myform" onSubmit="Objects[i++]=new Obj(text1.value,text2.value,text3.value)"> <b>Age:</b><input name="text1"> <b>Sex:</b><input name="text2"> <b>Location:</b><input name="text3"> <input type="submit"> </form> Ok,so knowing that each array element can store anything,including another object I used an Array to store each object instance.But is there any other way of storing objects? like in variables. Hello again everyone. I got this bit of code from "rnd me" and I guess I'm not as smart as I thought I was, because I was hoping to look at this code and figure out how to modify it to allow for nested Tables to be created but everything I try seems to make me scratch my head so I'm starting with the given code and hoping to get some help (again) Also on my prev post I can't get it to list as resolved Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>table maker</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head> <body> <table id="tab"> <tr id="i"> <td>hello world</td> </tr> </table> <script type='text/javascript'> var t=document.getElementById("tab"), //find table object base=document.createElement("tr"); //create template row base.appendChild(document.createElement("td")); //add a cell to template for (var i=1; i<10; i++){ var row=base.cloneNode(true); //dupe template row.id="row"+i; //assign id attrib using i and row prefix t.appendChild(row); //add new row to the table row.cells[0].innerHTML=Array(7).join(i);//insert dummy content }//next i </script> </body> </html> Is it possible to create an array of objects? I require a two dimensional array of objects. Thanks! Hello! I have a pretty straight forward question dealing with JQuery/Javascript (I'm pretty new to both, so the syntax is still escaping me). I have a javascript file that holds an array of objects inside of it (addresses to be exact) and I then need to take that array and call it to print into the Title attribute of a <li> after the list has been populated. Below is the Javascript arrray: Code: var banner_data = [ "address1","address2","address3","address4"]; var obj = { one:"address1", two:"address2", three:"address3", four:"address4" } And this is how it is being called in the HTML: Code: $('ul>li').each(function(){ var $this = $(this); // current list item var idx = $this.index(); var thisAddress = banner_data[idx]; $this.attr('title', thisAddress.append[4]) }); any thoughts? I have jQuery 1.7.1 installed, a fully valid html/css and a proper doctype (just to cover our bases haha) So, I'm using code like the following and getting errors: result = a list of cars with each property separated by ',' and each car separated by '|' This code creates and populates the array (seems to work) Code: var carList = new Array(); var cars = new Array(); var properties = new Array(); cars = result.split("|"); for(var i=0; i<cars.length;i++){ properties = cars[i].split(","); carlist[carlist.length++] = new car(items[0],items[1],items[2]); function car(id,make,model){ carID = id; carMake = make; carModel = model; } Later, I want to sort the array and call it like this: carList.sort(carSort); here's the sort code Code: function carSort(a, b){ var x = a.carMake.toLowerCase(); var y = b.carMake.toLowerCase(); return ((x < y) ? -1 : ((x > y) ? 1 : 0)); } I get the error that "a.carMake does not exist" (in firebug). What am I doing wrong? I have an array of objects that I would like to sort through and "join" objects that are the same. And if they are the same, I need to sum up the number value given for those two items. So I guess Im sorting through and maybe even recreating this array to get rid of duplicates while I tally quantities. Please see the screenshot of my array of objects to help understand better. The highlighted 'sPSPN' would indicate that it is a duplicate item and its 'fUnits' need to be totalled. in the end I would have a total of 3 objects, because 'sPSPN'= BT-221-44 would now be only one object with 'fUnits' = 35. Thanks! Hi If i was using c# i would use a generic list and add all my people objects to the list collection but how do i do this in jquery/javascript eg //container object var allObj= { }; //people object var people= { name:"fred",: age:00; }; How do I add many people objects to allObj (the amount of people added in not always the same) eg the final result is something like this allObj -person1 -person2 -person3 -person4 thanks Hello everybody am a JavaScript beginner. here is a code making rollovers //////////////////////////////////////////////// window.onload=rolloverInit; function rolloverInit() { for(var i=0; i<document.images.length; i++) { if(document.images.parentNode.tagName=="A") { setUpRollover(document.images); } } } function setUpRollover(currentImage) { currentImage.outImage = new Image(); currentImage.outImage.src = currentImage.src; currentImage.onmouseout = rollOut; currentImage.overImage = new Image(); var source = currentImage.src; var sourceText = source.toString(); if(sourceText.indexOf("png")>0) { currentImage.overImage.src ="images/"+currentImage.id+"_on.png"; } else { currentImage.overImage.src ="images/"+currentImage.id+"_on.gif"; } /*currentImage.overImage.src ="images/"+currentImage.id+"_on.gif";*/ /*currentImage.overImage.src ="images/"+currentImage.id+"_on.png";*/ currentImage.onmouseover = rollOver; currentImage.clickImage = new Image(); if(sourceText.indexOf("png")>0) { currentImage.clickImage.src ="images/"+currentImage.id+"_click.png"; } else { currentImage.clickImage.src ="images/"+currentImage.id+"_on.gif"; } /*currentImage.clickImage.src = "images/"+currentImage.id+"_on.gif";*/ /*currentImage.clickImage.src = "images/"+currentImage.id+"_on.png";*/ currentImage.onmousedown = rollClick; currentImage.parentNode.childImage = currentImage; currentImage.parentNode.onblur = rollOutParent; currentImage.parentNode.onfocus = rollOverParent; } function rollOut() { this.src = this.outImage.src; } function rollOver() { this.src = this.overImage.src; } function rollClick() { this.src = this.clickImage.src; } function rollOutParent() { this.childImage.src = this.childImage.outImage.src; } function rollOverParent() { this.childImage.src = this.childImage.overImage.src; } //////////////////////////////////////////////// 1-I do understand "if iam right, lol" that here ///currentImage.outImage = new Image();/// and here ///currentImage.overImage = new Image();/// and here ///currentImage.clickImage = new Image();/// we are creating an image object "overImage" on the fly which still a property of currentImage object, to keep track and store the current image and new image src. but here ///currentImage.parentNode.childImage = currentImage;/// I am unable to see the point behind creating the childImage object -same rule applied here??? is it really a brand new independent object "still a property of the parent" created on the fly like before? and if so -what is is purpose here?? how the cildImage object is interacting here, what is its purpose? and how it is able to modify "actually change" the <a> object child node Image object "currentImage". it seems stupid question but its quiet simple ---///currentImage.parentNode.childImage = currentImage;/// here I have an object on the fly, a new Image object "childImage", that is Fine until now. ---///this.childImage.src = this.childImage.outImage.src;/// now how the childImage became able to change my parent "<A>" child "currentImage" src ??? how it "childImage" became displayable at all is is because of the assignment here ///currentImage.parentNode.childImage = currentImage;/// ??? Yes i assigned currentImage to the childImage, but based on my java programing concepts background each still independent objects refrences representing two different objects ---->and so based on that here is these functions rollOutParent(), rollOverParent() am supposed to say something like ***this.currentImage.src = this.childImage.src*** or ***this.childImage.src = this.childImage.outImage.src;***or whatever "i know thats wrong coding here am just giving example". ------------ am confused, how with this simple line of code currentImage.parentNode.childImage = currentImage; childImage became able to define the currentImage ? and if so, how this was achieved, hoe the Objects is being represented and how they interact in the core memory? OK i'm trying to make an affiliate section for my page in javascript, I used double arrays and it's terribly coded. Please help. I'm new to this... Code: <html> <body> <script type="text/javascript"> var alley = new Array(); alley[0] = new Array( "http://stereo.b1.jcink.com/", "http://i49.tinypic.com/5klkb6.gif", "Stereo Wired" ); alley[1] = new Array ( "http://s1.zetaboards.com/N2010/", "http://sixpop.com/files/246/n2010.png", "N2010" ); alley[2] = new Array ( "http://theipodnation.net", "http://img15.imageshack.us/img15/1043/affiipod.png", "The Ipod Nation" ); for ( i = 3; i < alley.length; i++ ) { for ( m = 0; m < alley[i].length; m++ ) { document.write(" <a href='" + alley[i][m][0] + "'><img src='" + alley[i][m][1] + "' alt='" + alley[i][m][2] + "' /></a> ") } } </script> </body> </html> Hi, one of my js file is receiving a variable which is of type object. This object has some html texts. How can get the content of this object (something like value) in javascript? Thanks, Pavan Hello, Here is my situation. I have a java array generated from a JSP on the server side, and saved in the session. This array consists of objects (of say class X). How can I load this array into a javascript array so I can search for a this array based on attributes of the object? Thanks Hello, I have the following script, but I'd like to sort each nested array before it is written. How can I do this? I've tried putting Games.sort(); and Games[0].sort(); in different places, but it never seems to work. Code: var Games = new Array(); //PS3 Games[0] = new Array(); Games[0][0] = "ps3list"; Games[0][1] = "Uncharted: Among Thieves"; Games[0][2] = "Prince of Persia"; Games[0][3] = "Saboteur"; Games[0][4] = "Assassins Creed"; //Wii Games[1] = new Array(); Games[1][0] = "wiilist"; Games[1][1] = "Wii Play"; Games[1][2] = "Mario Party 8"; Games[1][3] = "Okami"; Games[1][4] = "Wii Sports"; function loadGames(){ for (i = 0; i < Games.length; i++) { var list = "<ul>"; for (j = 1; j < Games[i].length; j++) { list += "<li><input type = 'checkbox' class='checkbox' name = '" + Games[i][j] + "' />" + Games[i][j] + "</li>"; } list += "</ul>" document.getElementById(Games[i][0]).innerHTML = list; } } |