Anders Ekman
Anders Ekman

Reputation: 321

Find specific key/value in array of objects and print out another key/value in that object

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
    }]

Upvotes: -1

Views: 3021

Answers (3)

Rory McCrossan
Rory McCrossan

Reputation: 337701

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.

Upvotes: 1

guest271314
guest271314

Reputation: 1

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>

Upvotes: 0

pwilmot
pwilmot

Reputation: 596

using underscore you can get this with

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

see http://underscorejs.org/#findWhere

Upvotes: 0

Related Questions