0

I have the following for loop:

for (var i = 2; i < 7; i++) {
     if (cookieJSON.Cases.mdata+i.toString() == undefined)
          return i;

}

I want the object name to equal cookieJSON.Cases.mdata2 or cookieJSON.Cases.mdata3 or cookieJSON.Cases.mdata4 and so on.

How can I get this to work?

carloabelli
  • 4,161
  • 3
  • 38
  • 67
Dritzz
  • 149
  • 1
  • 1
  • 10

3 Answers3

0

Use brackets notation:

for (var i = 2; i < 7; i++) {
     if (cookieJSON.Cases["mdata" + i] == undefined)
          return i;
}

In JavaScript, you can access property names using either dot notation and a property name literal (foo.bar), or brackets notation and a property name string* (foo["bar"]). The string can be the result of any expression, including string concatenation.

* In ES6, the thing in the brackets can also be a Symbol, but that's not relevant to your question.

T.J. Crowder
  • 959,406
  • 173
  • 1,780
  • 1,769
0

You can put the key between brackets ([]) to form it from a string:

cookieJSON.Cases['mdata' + i]

Flame
  • 5,185
  • 3
  • 29
  • 45
0

Property Accessors

Property accessors provide access to an object's properties by using the dot notation or the bracket notation.

Syntax

object.property
object["property"]

E.g:-

for (var i = 2; i < 7; i++) {
      if (cookieJSON.Cases["mdata" + i] == undefined)
          return i;
}

More information here: Dot Notation vs Brackets

Community
  • 1
  • 1
Simpal Kumar
  • 3,765
  • 3
  • 26
  • 48