Iterate a JavaScript object with strings as keys

I am creating a JavaScript array that has strings as keys.

An array must have an object in each record. My object looks like this ( console.log my rIds variable):

Firebug screenshot of my variable

Now the length of this object is 0, which makes it impossible to repeat it.

I want to iterate over each key, so I can get and access my list of identifiers ( rIds[key].productIds ).

The 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 have i tried?

I found the following snippet that does not work in IE8. However, this does not really help, although 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 to the object.

Tl; dr and question

  • How to iterate my JavaScript object that has strings as keys, so I can access individual records?
+5
source share
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 is the venerable for ... in loop:

 for (var key in rIds) { if (rIds.hasOwnProperty(key)) console.log(rIds[key]); 

To support versions of IE prior to IE9, you seem to be stuck in for ... in , although you can find basically the right "polyfields" for Object.keys() and Array.prototype.forEach() in MDN.

+6
source

To add a Pointy answer , you can also use jQuery $.each (since you already use jQuery elsewhere) to rIds over each key / value pair in the rIds object:

 $.each(rIds, function(key, value) { console.log(value); }); 
+1
source

Source: https://habr.com/ru/post/1200679/


All Articles