5

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?
2
  • perhaps a jsfiddle would aid potential answerer Commented Aug 19, 2014 at 13:44
  • 4
    A JavaScript object with (non-numeric) strings as keys is not an array. Commented Aug 19, 2014 at 13:47

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

3 Comments

OP did mention this, but doesn't work in IE8 - so worth mentioning the alternative too.
@RGraham yes thanks I was thinking incrementally :) I took my dog for a walk instead of guzzling coffee this morning so my brain is slow.
Lol! Good responsible pet ownership :)
1

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);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.