当我将印度用作以下数据的输入时,我希望输出为 Delhi
{
data: [{
country: 'India',
capital: 'Delhi'
},
{
country: 'Pakisthan',
capital: 'Islamabad'
},
{
country: 'China',
capital: 'Beijing'
},
{
country: 'Bhutan',
capital: 'Thimphu'
}
]
}
答案 0 :(得分:3)
您可以使用Array.prototype.find方法:
var obj = {
data: [{
country: 'India',
capital: 'Delhi'
}, {
country: 'Pakisthan',
capital: 'Islamabad'
}, {
country: 'China',
capital: 'Beijing'
}, {
country: 'Bhutan',
capital: 'Thimphu'
}]
}
function getCapital(country, arr) {
return (arr.find(function(el) {
return el.country == country;
}) || {}).capital;
}
console.log(getCapital("India", obj.data)); // Delhi