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!
To access the JSON object in JavaScript, parse it with JSON. parse() , and access it via “.” or “[]”.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With