I have this response from a $.getJSON call. Now I want to select the name property of the object with "selected": true, and print it to a div with id charTitle.
"titles": [{
"id": 17,
"name": "Sergeant %s"
}, {
"id": 53,
"name": "%s, Champion of the Naaru"
}, {
"id": 64,
"name": "%s, Hand of A'dal",
"selected": true
}]
You can achieve this with a simple loop:
for (var i = 0; i < obj.titles.length; i++) {
if (obj.titles[i].selected) {
$('#charTitle').text(obj.titles[i].name);
}
}
Or with jQuery's $.each()
:
$.each(obj.titles, function(i, title) {
if (title.selected)
$('#charTitle').text(title.name);
});
Note that if you have multiple objects in the array with selected
set to true
you would need to use append()
instead of text()
to set the content of the div
, otherwise the previous value will be overwritten.