1

I have that object sample pages:

{
"page_1":
   {
     "stats":
       {
         "stat_1": 20,
         "stat_2": 40
       }
     "ahkam":
       {
         //Staff
       }
   }
"page_2":
   {
      //staff
   }
}

How can i get access to the value of stat_2? I used that expression but i don't know why it does not work:

Object.keys(pages["page_1"].stats)["stat_1"]
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Houssam Badri
  • 2,441
  • 3
  • 29
  • 60

3 Answers3

2

This is a visualisation of the data:

enter image description here

Therefore, to get there, you'd use:

var stat = pages.page_1.stats.stat_2;

If "page_1" is dynamic, then you can use the bracket notation (also known as the subscript notation):

var key = 'page_' + x;
var stat = pages[key].stats.stat_2;

If "stat_2" is also dynamic, then again, you can use the same notation:

var pageKey = 'page_' + x;
var statKey = 'stat_' + n;
var stat = pages[pageKey].stats[statKey];

Or you could use this notation for the whole expression:

var stat = pages[pageKey]['stats'][statKey];

Basically, a.b.c is equivalent to a['b']['c'], where in this case 'b' and 'c' are string literals, but can be any expression.

rid
  • 61,078
  • 31
  • 152
  • 193
  • page_1 is a variable, it is the key of parsing the object, it is in string format – Houssam Badri Jul 20 '13 at 09:33
  • @HoussemBdr, alright, then use the subscript notation. Example updated. – rid Jul 20 '13 at 09:33
  • FYI, it's called *bracket notation*. http://www.ecma-international.org/ecma-262/5.1/#sec-11.2.1 – Felix Kling Jul 20 '13 at 09:39
  • 1
    @FelixKling, it has many names, apparently. Crockford uses the term ["subscript notation"](http://javascript.crockford.com/survey.html). So if someone is looking it up, they should probably try both versions. Anyway, answer updated with both versions, thanks for the link. – rid Jul 20 '13 at 09:40
0

as

obj = { 
       field1: {
                stat1: "string";
       }
}


obj.field1.stat1
steo
  • 4,586
  • 2
  • 33
  • 64
0

is this not enough, Assign that object to var Page = {....}

  Page.page_1.stats.stat_1
Sarath
  • 9,030
  • 11
  • 51
  • 84