Javascript 在对象数组中查找特定的键/值,并打印出该对象中的另一个键/值

Javascript 在对象数组中查找特定的键/值,并打印出该对象中的另一个键/值,javascript,jquery,api,world-of-warcraft,battlenet-api,Javascript,Jquery,Api,World Of Warcraft,Battlenet Api,我从$.getJSON调用中得到了这个响应。现在我想用“selected”:true选择对象的name属性,并将其打印到id为charTitle的div中 "titles": [{ "id": 17, "name": "Sergeant %s" }, { "id": 53, "name": "%s, Champion of the Naaru" }, { "id": 64, "name

我从$.getJSON调用中得到了这个响应。现在我想用“selected”:true选择对象的name属性,并将其打印到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});

请参见尝试使用
Array.prototype.filter()

var-arr=[{
“id”:17,
“姓名”:“中士%s”
}, {
“id”:53,
“名称”:“%s,纳鲁的冠军”
}, {
“id”:64,
“名称”:“%s,阿达尔之手”,
“选定”:真
}]
var res=arr.filter(函数(val,键){
return val.selected==true
})[0]。名称;
$(“#charTitle”).html(res)

您可以通过一个简单的循环来实现这一点:

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

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

尝试使用下划线.js非常感谢!我从来没有意识到我可以循环遍历所有代码,只需查找selected/true,然后运行代码。现在开始看到循环的威力了!:)
$.each(obj.titles, function(i, title) {
    if (title.selected)
        $('#charTitle').text(title.name);        
});