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. Hope you can help!
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. Hope you can help!
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/
In addition to the other examples, you can get the properties out using the object[...]
syntax:
options["id"]
options["class"]
Also watch out with your example JSON. To be strictly valid JSON there should be quotes around the keys:
{ "id": "test_id", "class": "test_class" }