Using .each() to create nested Object out of table rows - javascript

I am desperately trying to create an Object while using the .each() loop but it doesn't seem to work. Here is the Code:
$("#pdfyap").on("click", function(){
var sonarr = {};
$("#bura tr").each(function(){
var malzemeadi = $(this).find(".maladi").html();
console.log(malzemeadi);
sonarr[malzemeadi] = {};
sonarr[malzemeadi]["malzemekodu"] = $(this).find(".malkodu").html();
sonarr[malzemeadi]["malzemedovizi"] = $(this).find(".doviz").html();
sonarr[malzemeadi]["malzemekdvorani"] = $(this).find(".kdvoranbir").html();
sonarr[malzemeadi]["malzemebirimfiyati"] = $(this).find(".birimfiyat").html();
sonarr[malzemeadi]["malzemebirimkdvmiktari"] = $(this).find(".kdvmikbir").html();
sonarr[malzemeadi]["malzemedovizfiyati"] = $(this).find(".dovfiyat").html();
});
sonarr["nettoplam"] = $("#aratop").html();
sonarr["kdvtoplam"] = $("#kdvtop").html();
sonarr["grosstoplam"] = $("#totaltry").html();
console.log(sonarr);
});
I get all the values right but in the console the object seems to have just the key (malzemeadi) and the value of it is empty and the last three ones are gotten right. long story short: just the nested ones are not being added, although the selector gets the values correct (checked it multiple times). What is it i am missing?
Here is the console log, too:
Object { sdfsadd: Object, fhg: Object, xcvxcv: Object, nettoplam: "6431", kdvtoplam: "245", grosstoplam: "6676" }
Thanks in advance.

I tried your code and it works. The problem is the console will only show the top-level items without expanding the hierarchy. Try clicking the little arrow next to the log to see the expanded hierarchy.
Alternatively, you can convert the object to JSON and log it to the console to see its hierarchy:
console.log(JSON.stringify(sonarr, null, 4));

Related

Having trouble referring to object within array

I am trying to write an html page for class that uses a drop down menu to allow users to pull up a list of relevant information. Unfortunately I am having trouble figuring out how to make the script call on the information in the array. The jsfiddle has the full html section, any help would be GREATLY appreciated.
Please bear in mind that I am not very good with terminology, so be as specific as possible. Especially regarding jQuery, our teacher didn't go over it much so it's a freaking mystery to me.
Also, I do plan on adding more information to the objects in the array, but until I get it working, I don't want to waste the time on something I might need to restructure.
http://jsfiddle.net/GamerGorman20/nw8Ln6ha/11/
var favWebComics = [
Goblins = {1: "www.goblinscomic.org"},
GirlGenious = {1: "www.girlgeniousonline.com"},
GrrlPower = {1: "www.grrlpowercomic.com"}
];
var myFunction = function() {
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
document.getElementById("web").innerHTML = favWebComics.x;
};
Again, the JSFiddle link has the full html, there are some unused items currently, but I do plan on adding more of them soon.
My next plan is to incorporate images into the objects, so a picture loads for each selection option. How would I manage that?
[ ] is used for arrays, which are indexed with numbers. If you want named properties, you should use an object, which uses { } for its literals:
var favWebComics = {
Goblins: "www.goblinscomic.org",
GirlGenious: "www.girlgeniousonline.com",
GrrlPower: "www.grrlpowercomic.com"
};
= is for assigning to variables, not specifying property names in an object.
Then you need to understand the difference between . and [] notation for accessing objects. .x means to look for a property literally named x, [x] means to use the value of x as the property name. See Dynamically access object property using variable.
So it should be:
document.getElementById("web").innerHTML = favWebComics[x];
your array is not structured correctly and an object would be better suited:
var favWebComics = {
Goblins : "www.goblinscomic.org",
GirlGenious : "www.girlgeniousonline.com",
GrrlPower : "www.grrlpowercomic.com"
};
then you should be able to access the properties as you intend
favWebComics.Goblins
favWebComics.GirlGenious
favWebComics.GrrlPower
Technically you were treating the array like a dictionary. if you're going to do that but still wanna add more information later you'll need to use brackets {} on the code.
var favWebComics = {
Goblins: ["www.goblinscomic.org"],
GirlGenious: ["www.girlgeniousonline.com"],
GrrlPower: ["www.grrlpowercomic.com"]
};
Also for javascript, as long as your searching key value stores, use braces [] for the call. Here's the working code below.
document.getElementById("web").innerHTML = favWebComics[x];
I have your solution, that displays:
the selected choice
the url
the images
Please check the fiddle.
http://jsfiddle.net/nw8Ln6ha/13/
Your object would be:
var favWebComics = {
Goblins : {url:"www.goblinscomic.org", img:"img1"},
GirlGenious : {url:"www.girlgeniousonline.com", img:"img2"},
GrrlPower : {url:"www.grrlpowercomic.com", img:"img3"}
};
Your display code:
document.getElementById("demo").innerHTML = "You selected: "+x+" "+ eval("favWebComics[\""+x+"\"].url")+" "+ eval("favWebComics[\""+x+"\"].img");

Get console.log() to display custom object description

I have a custom JS object that I've made to represent a grid. Stripped down for this example it looks like this:
function Grid(c, r)
{
var layout = [];
var contentPointer = 0;
this.getCell = function(c, r)
{
//Return selected cell
}
this.getRow = function(r)
{
//Return selected row
}
this.getCol = function(c)
{
//Return selected column
}
for(var row = 0; row < r; row++)
{
layout[row] = [];
for(var col = 0; col < c; col++)
layout[row][col] = 0;
}
}
I'm creating multiple instances of this here and there using var aGrid = new Grid(10, 10); and then manipulating them in various ways; adding/updating the contents of cells etc.
What I would like to be able to do is call console.log(aGrid); and be able to customise what is displayed by the console so I get, for instance, a string of all the cell values I've added or something similar.
In am used to Actionscript where we would use trace(aGrid); in place of console.log(aGrid); but in AS3 I could override the object's toString() method and that would update what is shown in the console output.
I have seen that I can add a toString() method to my Grid object in JS but the console does not seem to use it unless I specifically call console.log(aGrid.toString());. While this is fine, I just wondered if there is a way round this.
Does the console actually generate it's output based on some overridable method of the object being logged or does it do some crazy internal magic to get a value?
using alert(aGrid); seems to use toString() and picks up the custom value but I would rather peel my own skin off than debug a big project using alert(); :)
Any and all comments very welcome. Thank you.
PS - I don't know if different browsers treat console.log() differently but I am using Chrome v33.
I have seen that I can add a toString() method to my Grid object in JS but the console does not seem to use it unless I specifically call console.log(aGrid.toString());. While this is fine, I just wondered if there is a way round this
No, there is no way around this. The console alone does decide how to display the passed arguments - and Chrome console lets you dynamically inspect objects instead of trying to serialize them somehow. If you want a custom output, you will need to pass it a string.
console.log accepts Object as argument(s), and if you put it there, you will be able to inspect it in Chrome console.
So remove .toString() and it will do the trick
console.log("aGird", aGrid );
You can use console.table() for this. console.table allows you to specify what properties would you like to view. For instance
console.table(aGrid); // will show all properties
console.table(aGrid, 'firstName'); // will show only firstName property
console.table(aGrid, ['firstName', 'lastName']); // will show firstName and lastName properties

Need to get an array of the names of all applicationScope variables

In an application I am working on I need to get a list of the names of all applicationScope variable then I need to cycle through them and filter out the ones starting with a know string say $xyx. I thought that the applicationScope.keySet().
I'm using this code for starter:
var col = applicationScope.keySet();
var itr:java.util.Iterator = col.iterator();
if (itr.hasNext()){
var str:String = itr.next();
dBar.info(str,"Value = ");
}
if I put the variable col in a viewScope it shows a list of all the keys. but when I run the script the values displayed in the dBar info are not the keys but some other information that I'm not sure where it comes from.
I should just be able to iterat through the list of keys, am I missing something?
This code is in the before page loads event
After some poking around and experimenting I got this to work:
var col = applicationScope.keySet();
var itr:java.util.Iterator = col.iterator();
while (itr.hasNext()){
var str:Map.Entry = itr.next();
if (str.substring(0,9) == "$wfsLock_"){
//do stuff
}
}
so I'm now a happy camper.
Although your code works in SSJS, it is not correct (and that's why I don't like SSJS...).
The applicationScope is an implementation of the java.util.Map interface and the keySet() method returns a Set containing the keys in that Map. Every entry is (probably) a String (other data types like integers are actually also valid). The line
var str:Map.Entry = itr.next();
doesn't cast it to a Map.Entry: it doesn't really do anything: str remains a string.
The Map interface also has an entrySet() method that returns the entries (Map.Entry). You can use that to retrieve the key as well as the value:
var it = applicationScope.entrySet().iterator();
while (it.hasNext()) {
var entry = it.next();
print( entry.getKey() + " = " + entry.getValue() );
}
(in this code the print() line will use the toString() method of the key as well as the value to send information to the console)
I see from your code that you've installed my XPages Debug Toolbar. You can also use that to quickly check what's in the scopes and what the actual datatype is.

Can't change value of a variable in JS, using parseFromString

I have this line at the very beginning of a Chrome extension:
var macroXML = parser.parseFromString(localStorage["myMacro"], "text/xml").getElementsByTagName("section");
After doing some changes, I try to update macroXML, but nothing happens.
alert(macroXML[1]);
macroXML[1] = 'RAWR';
alert(macroXML[1]);
No errors, no anything. It outputs the exact same thing.
Anyone perhaps know why?
You are dealing with a dynamic nodes list. It will change if the document changes, e.g. to remove the second element from the list you can do:
macroXML[1].parentNode.removeChild(macroXML[1]);
Or you replace it by a different node:
var newNode = macroXML[1].ownerDocument.createElement("section");
macroXML[1].parentNode.replaceChild(newNode, macroXML[1]);
But you cannot work with that list as you would do with an array - for that you need an actual array. You can copy the list like this:
var macroArray = Array.prototype.slice.apply(macroXML);
macroArray[1] = 'RAWR';
This will work as expected then.

JSON how find another value at the same index from a value in Javascript Object

A simple question I'm sure, but I can't figure it out.
I have some JSON returned from the server
while ($Row = mysql_fetch_array($params))
{
$jsondata[]= array('adc'=>$Row["adc"],
'adSNU'=>$Row["adSNU"],
'adname'=>$Row["adname"],
'adcl'=>$Row["adcl"],
'adt'=>$Row["adt"]);
};
echo json_encode(array("Ships" => $jsondata));
...which I use on the client side in an ajax call. It should be noted that the JSON is parsed into a globally declared object so to be available later, and that I've assumed that you know that I formated the ajax call properly...
if (ajaxRequest.readyState==4 && ajaxRequest.status==200 || ajaxRequest.status==0)
{
WShipsObject = JSON.parse(ajaxRequest.responseText);
var eeWShips = document.getElementById("eeWShipsContainer");
for (i=0;i<WShipsObject.Ships.length;i++)
{
newElement = WShipsObject.Ships;
newWShip = document.createElement("div");
newWShip.id = newElement[i].adSNU;
newWShip.class = newElement[i].adc;
eeWShips.appendChild(newWShip);
} // end for
}// If
You can see for example here that I've created HTML DIV elements inside a parent div with each new div having an id and a class. You will note also that I haven't used all the data returned in the object...
I use JQuery to handle the click on the object, and here is my problem, what I want to use is the id from the element to return another value, say for example adt value from the JSON at the same index. The trouble is that at the click event I no longer know the index because it is way after the element was created. ie I'm no longer in the forloop.
So how do I do this?
Here's what I tried, but I think I'm up the wrong tree... the .inArray() returns minus 1 in both test cases. Remember the object is globally available...
$(".wShip").click(function(){
var test1 = $.inArray(this.id, newElement.test);
var test2 = $.inArray(this.id, WShipsObject);
//alert(test1+"\n"+test2+"\n"+this.id);
});
For one you can simply use the ID attribute of the DIV to store a unique string, in your case it could be the index.
We do similar things in Google Closure / Javascript and if you wire up the event in the loop that you are creating the DIV in you can pass in a reference to the "current" object.
The later is the better / cleaner solution.
$(".wShip").click(function(){
var id = $(this).id;
var result;
WShipsObject.Ships.each(function(data) {
if(data.adSNU == id) {
result = data;
}
});
console.log(result);
}
I could not find a way of finding the index as asked, but I created a variation on the answer by Devraj.
In the solution I created a custom attribute called key into which I stored the index.
newWShip.key = i;
Later when I need the index back again I can use this.key inside the JQuery .click()method:
var key = this.key;
var adt = WShipsObject.Ships[key].adt;
You could argue that in fact I could store all the data into custom attributes, but I would argue that that would be unnecessary duplication of memory.

Categories

Resources