0

I have a global namespace of constants, how to I dynamically loop through these?

$.sKey = {
    k1: '9t1q6g',
    k2: 'o849nc',
    k3: 'xs96hn',
    k4: 'jb24nc',
    k5: 'iqokpb'
};

I have tried adaptations of the following:

for(var i = 0; i < 4; i++) 
    alert($.skey.k + i);
}
Matt D. Webb
  • 3,216
  • 4
  • 29
  • 51

5 Answers5

3

Using a foreach loop:

for (var key in $.sKey) alert($.sKey[key]);
sp00m
  • 47,968
  • 31
  • 142
  • 252
1

loop through the js object with

for (var k in $.sKey) {

and check if the attribute is not inherited. like

if ($.sKey.hasOwnProperty(k)) {

like

for (var k in $.sKey) {
      if ($.sKey.hasOwnProperty(k)) {
        console.log(k,$.sKey[k]);
      }
}

Here is a sample fiddle

Mithun Satheesh
  • 27,240
  • 14
  • 77
  • 101
-1

like this

for(var key in $.sKey) 
    {
         alert($.sKey[key]);
    }
alexislg
  • 1,018
  • 13
  • 20
-1

Use each in jquery to retrieve all data

 $.each($sKey,function(i,val){
alert(val);
});

DEMO

Balachandran
  • 9,567
  • 1
  • 16
  • 26
-2

if you are using jquery you can change your codes into this:

var sKey = {
k1: '9t1q6g',
k2: 'o849nc',
k3: 'xs96hn',
k4: 'jb24nc',
k5: 'iqokpb'
};
$.each(sKey,function(key,value){
    console.log("key:"+key+"value:"+value);
})

You can see a jsfiddle here

user2854865
  • 65
  • 1
  • 3