0

In JavaScript, I have a JSON Object. This JSON Object has many keys and I need to access one stored in as a String using the dot operator but am not sure how to do this.

For example, if I have the following JSON code:

"values" : [ { "prop0" : "h",
        "prop1" : "pizza",
        "prop2" : "2014-06-24T15:58:50Z",
        "prop3" : ""
      },
      { "prop0" : "paa",
        "prop1" : "cat",
        "prop2" : "2014-06-24T15:58:16Z",
        "prop3" : "mouse"
      }
    ]

and I want to access prop1 I would use the following JavaScript code:

values[0].prop1;

This works so long as I know that the property is called prop1. But I don't know what my properties will be called. I have a String that represents what, in this case, is prop1 or whatever the current property is, however I don't know how to use the dot operator with a String.

I would like something like:

values[0].myString;

But this does not work.

Is there a way to do what I am trying to achieve?

Barmar
  • 741,623
  • 53
  • 500
  • 612
feztheforeigner
  • 317
  • 1
  • 4
  • 12

3 Answers3

1

You can treat a javascript object as an associative array or dictionary by passing it a key to lookup:

values[0][myString]

In the following code,

var myString = 'prop1';
var val1 = values[0][myString];
var val2 = values[0].prop1;

val1 and val2 both hold a value of 'pizza'

Jonathan Wilson
  • 4,138
  • 1
  • 24
  • 36
0

Use bracket notation.

values[0].myString is equivalent to values[0]['myString'] :)

For example,

var obj = { a : 1 };
obj.a // returns 1
var a_string = 'a';
obj[a_string] // returns 1

In general, dot notation looks cleaner but bracket notation is convenient for exactly this purpose.

Liam Horne
  • 857
  • 1
  • 7
  • 15
  • but only if `myString` is actually the name of the property. I think the question is about looking up a property where the name of the property is in a variable. – Jonathan Wilson Jun 27 '14 at 23:49
  • Right, I'm just showing that you can pass in a string like a dictionary lookup with a literal, so that means passing in a string variable will work how he expects. Added an example though. – Liam Horne Jun 27 '14 at 23:51
0

In Javascript you can access properties with dot notation(the way you've been doing it) and with flat bracket notation(i.e. []), so you should be able to access it like this:

values[0][myString]

euwest
  • 31
  • 4