I am trying to use a hashtable so I can select a specific object stored in an array/object. However, I am having a problem looping through an object.
var pins= {}; pins[6] = '6'; pins[7] = '7'; pins[8] = '8'; $('#result3').append('<div>Size: ' + Object.size(pins) + '</div>'); for(var i = 0; i < Object.size(pins); i++) { $('#result3').append('<div>' + pins[i] + '</div>'); }
JSFiddle: http://jsfiddle.net/7TrSU/
As you can see in TEST 3
which uses object pin
to store the data, I am getting undefined
when looping through the object pin
.
What is the correct way for looping through pin
?
EDIT
What happens if instead of just pin[6] = '6'
, I make pin[6] = an object and I want to loop through the all their id
properties? Actual code snippet of what I'm doing...
for(var i = 0; i < json.length; i++) { markerId = json[i].listing_id // Place markers on map var latLng = new google.maps.LatLng(json[i].lat, json[i].lng); var marker = new google.maps.Marker({ listing_id: markerId, position: latLng, icon: base_url + 'images/template/markers/listing.png', }); markers[markerId] = marker; } for(var marker in markers) { console.log('marker ID: ' + marker.listing_id); mc.addMarker(marker); }
The console.log
above returns undefined, and if I do console.log(marker)
instead, I get the value of marker.listing_id
. Sorry I'm getting confused!
I managed to get it to work with $.each(markers, function(i, marker){});
but why does the for..in
above not work?
In the first method, the one that I prefer, you can use the GetEnumerator method of the hash table object. In the second method, instead of iterating over the hash table itself, we loop over the Keys of the hash table. Both of these methods produce the same output as our original version.
Hashtable will change the iterator by using Enumerator interface. Yes,we can iterate a hashmap using the entrySet() method.
Printing hashtable: To print /display a hashtable, just type the variable name in which hashtable is saved. The above command displays a table with two columns, one for keys and the other one for the associated values for the keys.
In computing, a hash table, also known as hash map, is a data structure that implements an associative array or dictionary. It is an abstract data type that maps keys to values.
var hash = {} hash[key] = value Object.keys(hash).forEach(function (key) { var value = hash[key] // iteration code })
Don't use a for(i=0; i<size; i++)
loop. Instead, use:
Object.keys(pins)
to get a list of properties, and loop through it, orfor ( key_name in pins)
in conjunction with Object.hasOwnProperty
(to exclude inherit properties) to loop through the properties.The problem of your third test case is that it reads the values of keys 0, 1 and 2 (instead of 6, 7, 8).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With