Iterating through an object hashtable
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?
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, or - Use a
for ( key_name in pins)
in conjunction withObject.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).
Since you are using jQuery:
jQuery.each(pins, function (name, value) {
$('#result3').append('<div>' + name + "=" + value + '</div>');
});
Try this:
for (var pin in pins) {
$('#result3').append('<div>' + pin + '</div>');
}
Example fiddle