在对象数组中查找特定的 key/value 并在该对象中打印出另一个 key/value

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

我收到了来自 $.getJSON 调用的响应。现在我想 select 带有 "selected" 的对象的名称 属性: true,并将其打印到带有 id charTitle 的 div。

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

使用下划线你可以用

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

http://underscorejs.org/#findWhere

尝试使用 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>

你可以用一个简单的循环来实现:

for (var i = 0; i < obj.titles.length; i++) {
    if (obj.titles[i].selected) {
        $('#charTitle').text(obj.titles[i].name);
    }
}

Example fiddle

或 jQuery 的 $.each():

$.each(obj.titles, function(i, title) {
    if (title.selected)
        $('#charTitle').text(title.name);        
});

请注意,如果数组中有多个对象 selected 设置为 true,则需要使用 append() 而不是 text() 来设置内容div,否则之前的值将被覆盖。