I am building a JavaScript array, which has strings as keys.
The array should have an object at every entry. My object looks like this (a console.log of my variable rIds):

Now, the length of this object is 0, which makes it impossible to iterate it.
I want to iterate every key, so I can retrieve and access my list of ids (rIds[key].productIds).
Code:
var rIds = [];
        var response = RR.data.JSON.placements;
        console.log(response);
        $(response).each(function (placementId) {
            var placement_name = this.placement_name;
            rIds[this.placement_name] = {
                productIds: []
            };
            $(this.recs).each(function (recIndex) {
                var pid = this.pid;
                pid = getRandomId(19341610, 19341746);
                rIds[placement_name].productIds[recIndex] = pid;
            });
        });
        var count = '<%=ViewBag.Get("RecommendationCount") %>';
        console.log(rIds);
        console.log(rIds.length);
        $.each(rIds, function (index, val) {
            console.log(val);  // This should work as expected.
        });
What did I try?
I found the following snippet, which does not work in IE8. However, this does not really help be, even though Object.keys(rIds).length results in the correct length.
for (var index = 0; index < Object.keys(rIds).length; index++) {
            console.log(rIds[index]);
        }
However, this code does not make my access the object.
Tl;dr & question
The Object.keys() function returns an array containing the property names of the object.
var keys = Object.keys(rIds);
for (var i = 0; i < keys.length; ++i) {
  console.log(rids[keys[i]]); // object value
}
Alternatively, you can use the .forEach() method:
Object.keys(rIds).forEach(function(key) {
  console.log(this[key]);
}, rIds);
Finally there's the venerable for ... in loop:
for (var key in rIds) {
  if (rIds.hasOwnProperty(key))
    console.log(rIds[key]);
To support versions of IE before IE9 you're kind-of stuck with for ... in, though you can find mostly-correct "polyfills" for Object.keys() and Array.prototype.forEach() at MDN.
To supplement Pointy's answer, you can also use jQuery's $.each (since you're already using jQuery elsewhere) to iterate over each key/value pair in your rIds object:
$.each(rIds, function(key, value) {
    console.log(value);
});
                        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