0

Say i have object like

var a = {"user":
                {'average':
                           {'score':4
                           }
                }
         }

How can I read object value using its keys

Say I have user Object with me and have key "average.score" can I get the value directly?

a.user["average.score"];
//Coming as undefined
a.user["average"]["score"]
// Working as expected  : 4

I have the key of "average.score" all together with me want to get the value of score how can I do it directly without splitting the key.

Kunal Vashist
  • 2,380
  • 6
  • 30
  • 59

1 Answers1

-2

Use a.user["average"].score

var a = {"user":
                {'average':
                           {'score':4
                           }
                }
         }
         
         console.log(a.user["average"].score);
JSON Derulo
  • 9,780
  • 7
  • 39
  • 56
  • That's no different than `a.user.average.score`. – Mohit Bhardwaj Jul 20 '17 at 06:16
  • Like the author said, the "average" string is dynamic. Mycode snippet is just for understandig the concept. I totally don't understand why you are downvoting my answer. – JSON Derulo Jul 20 '17 at 06:20
  • I did not downvote your answer. But it's incorrect. You are using a string in square brackets `"average"`. It will always look for `average` key. If `average` is a variable you should use it without quotes - `a.user[average].score`. – Mohit Bhardwaj Jul 20 '17 at 06:22