Accessing a JSON property (String) using a variable

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.

Leave a Comment