0

I have an array of objects and I want to extract the value when key is passes in 'filter' filter. Below is the controller code snippet I have tried, but the type of response I get is undefined. Please help me in finding where am I going wrong.

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. I have injected $filter in the controller

3
  • pls show your filter Commented Apr 12, 2018 at 11:29
  • @Prastheesh I am using 'filter' filter provided by AngularJS Commented Apr 12, 2018 at 12:04
  • You need to create a custom filter for that. Check the answers for this question. It is a similar problem. stackoverflow.com/questions/14788652/… Commented Apr 13, 2018 at 3:24

1 Answer 1

1

Use Object.keys and find

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

Demo

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Gurvinder. The solution is working fine. Wanted to know if it can be done with filter in AngularJs
Sorry, I am not aware how to use filter in AngularJS to solve your problem. Vanilla JS solutions works for me, so never needed another library for such trivial tasks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.