Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a JSON property (String) using a variable

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!

like image 734
Chiqui Esteban Avatar asked Oct 10 '13 15:10

Chiqui Esteban


People also ask

How do I access elements in JSON?

To access the JSON object in JavaScript, parse it with JSON. parse() , and access it via “.” or “[]”.

Are variables allowed in JSON?

Variables provide a new way to tackle different scenarios where JSON schema alone fails. This means, that you can use a new keyword named $vars to make your life easier.


1 Answers

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.

like image 83
Brad Christie Avatar answered Sep 20 '22 21:09

Brad Christie