2

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');

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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;

Comments

0

You can access an object as an associative array too.

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

1 Comment

there's no such thing as a "JSON object".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.