I have a javascript function create(tagName, options) and the options variable is a JSON object. like this:
{id: 'test_id', class: 'test_class'}
I would like to know how to get the 'id/class' part of the json object.
You can use dot or square bracket notation:
var obj = {id: 'test_id', klass: 'test_class'};
alert(obj.id + ' ' + obj.klass);
or:
var obj = {id: 'test_id', klass: 'test_class'};
alert(obj['id'] + ' ' + obj['klass']);
You can use a for...in loop to get the keys, e.g.:
var obj = {id: 'test_id', klass: 'test_class'};
for(key in obj) {
alert(key);
}
Demo: http://jsfiddle.net/2p2gw/5/
class is a future reserved word, and some implementations may throw a SyntaxError exception if used as an Identifier. Safari is a good example, the demo will not work.
classis a reserved word in ECMAScript spec. Nothing will break yet since it is not reserved yet in implmentation, but it is a good idea to put the keys in quotes as well.{'id': 'test_id', 'class': 'test_class'}klassinstead ofclass.