我有一个对象数组,我希望在密钥传入'过滤器'时提取值。过滤。下面是我尝试过的控制器代码片段,但我得到的响应类型是未定义的。请帮助我找到我错在哪里。
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
答案 0 :(得分:1)
使用Object.keys
和find
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);