-1

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
    }]
Anders Ekman
  • 323
  • 5
  • 17

3 Answers3

1

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);
    }
}

Example fiddle

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.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Thank you so much! I never realized I could loop through it all and just look for the selected/true and then run code. Starting to see the power of loops now! :) – Anders Ekman Nov 27 '15 at 04:41
0

using underscore you can get this with

var titles = ...
_.findWhere(titles, {selected: true});

see http://underscorejs.org/#findWhere

pwilmot
  • 586
  • 2
  • 8
0

Try using Array.prototype.filter()

var arr = [{
  "id": 17,
  "name": "Sergeant %s"
}, {
  "id": 53,
  "name": "%s, Champion of the Naaru"
}, {
  "id": 64,
  "name": "%s, Hand of A'dal",
  "selected": true
}]

var res = arr.filter(function(val, key) {
  return val.selected === true
})[0].name;

$("#charTitle").html(res)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="charTitle"></div>
guest271314
  • 1
  • 15
  • 104
  • 177