3

I have the next code in javascript. I deleted some unnecessary items because it went to long.

var options = {
    dhcode: true,
    commands: {
        bold: {
            enabled: true,
            view: true,
            exec: true,
            cmd: 'bold',
            param: null
        },
        italic: {
            enabled: true,
            view: true,
            exec: true,
            cmd: 'italic',
            param: null
        },
        underline: {
            enabled: true,
            view: true,
            exec: true,
            cmd: 'underline',
            param: null
        }
    }
}

Now i want to get al data in the options.commands object. But everything what i try don't work. This is what i am trying:

for(var i=0;i<options.commands.length;i++) {
alert(options.commands[i].cmd);
}

Please help me.

ghoppe
  • 21,452
  • 3
  • 30
  • 21
Timo
  • 7,195
  • 7
  • 24
  • 25

3 Answers3

8

.length is a property of arrays, what you have is an object.

Try:

for(var key in options.commands) {
    alert(options.commands[key].cmd);
}
sorpigal
  • 25,504
  • 8
  • 57
  • 75
2

Have a look at how-to-loop-through-javascript-object-literal-with-objects-as-members.

Essentially:

for (var key in options.commands) {
   alert(  options.commands[key].enabled );
   ...
}
Community
  • 1
  • 1
Justin Ethier
  • 131,333
  • 52
  • 229
  • 284
1
for(var i in options.commands){
   alert(i); //bold, italic, underline
   alert(options.commands[i].cmd);
}
Jage
  • 7,990
  • 3
  • 32
  • 31