'过滤器'在AngularJS中过滤

时间:2018-04-12 11:18:25

标签: javascript arrays angularjs

我有一个对象数组,我希望在密钥传入'过滤器'时提取值。过滤。下面是我尝试过的控制器代码片段,但我得到的响应类型是未定义的。请帮助我找到我错在哪里。

var states =  [{"HIMACHAL PRADESH":"HP"},{"JAMMU AND KASHMIR":"JK"},{"JHARKHAND":"JH"},{"KARNATAKA":"KA"},{"KERALA":"KL"},{"MADHYA PRADESH":"MP"},{"MAHARASHTRA":"MH"},{"ORISSA":"OR"}]
var str = "ORISSA";
var abbr = $filter('filter')(states, {key: str}, true).value;
console.log ("ABBR:"+abbr);

P.S。我在控制器中注入了$ filter

1 个答案:

答案 0 :(得分:1)

使用Object.keysfind

var matchedState = states.find( s => Object.keys( s )[0] == str );
var abbr = matchedState ? matchedState[str] : ""

<强>演示

var states = [{
  "HIMACHAL PRADESH": "HP"
}, {
  "JAMMU AND KASHMIR": "JK"
}, {
  "JHARKHAND": "JH"
}, {
  "KARNATAKA": "KA"
}, {
  "KERALA": "KL"
}, {
  "MADHYA PRADESH": "MP"
}, {
  "MAHARASHTRA": "MH"
}, {
  "ORISSA": "OR"
}]
var str = "ORISSA";
var matchedState = states.find(s => Object.keys(s)[0] == str);
var abbr = matchedState ? matchedState[str] : ""
console.log(abbr);