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!
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!
Share Improve this question asked Oct 10, 2013 at 15:36 Chiqui EstebanChiqui Esteban 4213 gold badges6 silver badges12 bronze badges 4-
If category is a string containing the key of the JSON property, it'd be as easy as
console.log(data[category])
– devnull69 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? – devnull69 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. – Guffa Commented Oct 14, 2014 at 23:10
- Does this answer your question? Dynamically access object property using variable – Ivar Commented Feb 21, 2021 at 0:53
1 Answer
Reset to default 23data[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 ing 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.