Iterating through an object hashtable

Nyxynyx picture Nyxynyx · Apr 8, 2012 · Viewed 72.4k times · Source

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?

Answer

Raynos picture Raynos · Apr 8, 2012
var hash = {}
hash[key] = value

Object.keys(hash).forEach(function (key) { 
    var value = hash[key]
    // iteration code
})