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,289
  • 3
  • 43
  • 70
Dritzz
  • 159
  • 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
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

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

cookieJSON.Cases['mdata' + i]

Flame
  • 6,663
  • 3
  • 33
  • 53
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
SK.
  • 4,174
  • 4
  • 30
  • 48