9

I'm trying to access a JSON using a variable I'm passing through a function:

function highlightCategory (category) {
   for (var i in data) {
      console.log(data[i].category)
   }
}

Obviously, this doesn't work, because 'category' is what I'm passing with the function and not the real name of the property, but I've been trying different possibilities unsuccessfully. Thanks in advance!

4
  • If category is a string containing the key of the JSON property, it'd be as easy as console.log(data[category]) Commented Oct 10, 2013 at 15:37
  • 1
    It'd help if you showed your JSON ... is "category" a direct property of data or is it a sub-property of one of the direct properties? Commented Oct 10, 2013 at 15:40
  • Note: That's not JSON, that is a Javascript object. JSON is a text format to represent objects. Commented Oct 14, 2014 at 23:10
  • Does this answer your question? Dynamically access object property using variable Commented Feb 21, 2021 at 0:53

1 Answer 1

24
data[i][category]

in JS, obj.prop is synonymous with obj['prop'].

var foo = {
  bar: 'baz'
};
// foo.bar == foo['bar'] == 'baz'

Also, you're dealing with a javascript object, not JSON (though it may have originated there)

Update for those coming across this and using ES6, you can now use variables during assignment:

const propName = 'bar';
const foo = {
  [propName]: 'baz',
}
// foo.bar == foo[propName] == 'baz'

For reference, this is considered a ComputedPropertyName under Object Initializer section of ES6 spec.

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

3 Comments

Brad's answer works! Thanks. I just forgot to get rid of the dot (data[i].[category]).
@ChiquiEsteban, if it works you should accept the answer by clicking the checkbox to the left
@Austin: Probably still too soon to accept. ;-) But thanks for the enthusiasm.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.