如何从对象返回特定数据

时间:2020-04-15 12:16:34

标签: javascript arrays javascript-objects

当我将印度用作以下数据的输入时,我希望输出为 Delhi

{
  data: [{
      country: 'India',
      capital: 'Delhi'
    },
    {
      country: 'Pakisthan',
      capital: 'Islamabad'
    },
    {
      country: 'China',
      capital: 'Beijing'
    },
    {
      country: 'Bhutan',
      capital: 'Thimphu'
    }
  ]
}

1 个答案:

答案 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

相关问题