gpt4 book ai didi

javascript - AngularJS 中的“过滤器”过滤器

转载 作者:行者123 更新时间:2023-12-03 02:06:13 26 4
gpt4 key购买 nike

我有一个对象数组,我想在键传入“filter”过滤器时提取值。下面是我尝试过的 Controller 代码片段,但我得到的响应类型未定义。请帮我找出哪里出错了。

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);

附注我已在 Controller 中注入(inject) $filter

最佳答案

使用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);

关于javascript - AngularJS 中的“过滤器”过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49795157/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com