Jonathan de M.
Jonathan de M.

Reputation: 9808

Use a variable as attribute for an object, how to?

For the following tree

var items = {
  'drinks': [
    {
      'name': 'coke',
      'sugar': '1000'
    },
    {
      'name': 'pepsi',
      'sugar': '900'
    }
  ]
};

Is there a way to do something like

function get_values(data) {
  var items = JSON.parse(items)
  return items.data[0].name;
}
get_values('drinks');

Upvotes: 2

Views: 270

Answers (3)

Alnitak
Alnitak

Reputation: 339816

If you wish to use the contents of a variable as the accessor for a property, you must use array syntax:

myObject[myKey]

In your case, you need something like:

var items = JSON.parse(items)

function get_values(data) {
    return items[data][0].name;
}

get_values('drinks');  // returns "coke"

Note that this is specifically only returning the name of the first element in the array items.drinks.

Upvotes: 3

Mārtiņš Briedis
Mārtiņš Briedis

Reputation: 17762

You can access an object as an associative array too.

console.log(items['drinks']);

Upvotes: 0

Mathias Bynens
Mathias Bynens

Reputation: 149564

Simply access the property value based on its name.

Using bracket notation:

items['drinks'];

Or, using dot notation, which is possible in this case:

items.drinks;

Upvotes: 2

Related Questions