Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating JavaScript object with strings as keys

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):

Firebug screenshot of my variable

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

  • How do I iterate my JavaScript object which has strings as keys, so I can access the individual entries?
like image 891
Lars Holdgaard Avatar asked Aug 19 '14 13:08

Lars Holdgaard


2 Answers

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.

like image 77
Pointy Avatar answered Sep 28 '22 00:09

Pointy


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);
});
like image 35
apsillers Avatar answered Sep 27 '22 23:09

apsillers