0
var obj = {
   height: 160,
   width: 140,
   color: "green"
}

var x = "color";

console.log(obj.x);

I want to get "green" but I get An Error.

Taplar
  • 24,788
  • 4
  • 22
  • 35
Kim Ber
  • 69
  • 11
  • 2
    Just so you are aware for next time. It's best practice to include what error you are getting instead of `but I get An Error`. Actually posting the error you get with additional detail helps us help you. – Charlie Fish Jan 03 '19 at 19:40
  • console.log(obj[x]); – Achraf Jan 03 '19 at 19:40
  • Refer to this post https://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable – Praveen Govind Jan 03 '19 at 19:43

2 Answers2

3

You need square bracket notation:

var obj = {
   height: 160,
   width: 140,
   color: "green"
}

var x = "color";

console.log(obj[x]);
ic3b3rg
  • 14,629
  • 4
  • 30
  • 53
  • 2
    Why is this answer getting downvotes? Doesn't make sense to me. It's a perfectly legit answer that works and answers the question. – Charlie Fish Jan 03 '19 at 19:39
  • 3
    because this answer has been asked/answered again and again. It does not make sense to me if we provide solutions again to a such general problem. It's more convenient to mark it as duplicate and point to the original question – quirimmo Jan 03 '19 at 19:41
  • 2
    IMHO, It's a legit answer for a legit question. – M. Gara Jan 03 '19 at 19:46
  • 1
    @quirimmo Doesn't mean the answer should be downvoted. If anything the question should be downvoted. Providing a good answer shouldn't be downvoted because the person asking the question didn't put time into researching and Googling before asking. That is on the person asking the question, not the person answering the question. – Charlie Fish Jan 03 '19 at 21:46
  • 1
    @CharlieFish fair enough, actually, you are right. Removed my downvote from the answer – quirimmo Jan 03 '19 at 21:56
-4

I think you are confused about how Objects work in Javascript. For example here's a much cleaner way to access the colors in an Object.

var obj = {
   height: 160,
   width: 140,
   color: "green"
}

console.log(obj.color)

For more information on how Objects work, checkout this link -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

buoyantair
  • 347
  • 4
  • 11
  • Isn't there a chance that the variable `x` is a dynamic variable? Using bracket notion I think better answers the question. – Charlie Fish Jan 03 '19 at 19:40