简体   繁体   中英

How to filter JSON data using Typescript / Javascript / Angular 4?

I have json data like this

data :[
{taskname:'chennai',    id:'maa' }
{taskname:'mumbai',     id:'bom' }
{taskname:'delhi',      id:'del' }
....
....
....
{taskname:'salem',      id:'che'}
{taskname:'bengaluru',  id:'blr'}
{taskname:'chavvapet',  id:'chv'}
}]

now i need to filter this data and return matching values (just like autocomplete). For example when i get value CH , first i need to check on ID and then on taskname . so the return value should be like this. must order ID matching top and then taksname matching.

{taskname:'salem',      id:'che'}
{taskname:'chavvapet',  id:'chv'}
{taskname:'chennai',    id:'maa'}

Incase if i get value CHE, then i need to return value like this

{taskname:'salem',      id:'che'  }
{taskname:'chennai',    id:'maa'  }

Could someone please tell me how to do filter using typescript ?

Tried few of this answer , but no luck.

Try this code

 const data = [ {taskname:'chennai', id:'maa',status:'Submitted'}, {taskname:'mumbai', id:'bom',status:'Resolved'}, {taskname:'delhi', id:'del',status:'Submitted'}, {taskname:'salem', id:'che',status:'In Progress'}, {taskname:'bengaluru',id:'blr',status:'Resolved'}, {taskname:'chavvapet',id:'chv',status:'Submitted'} ]; function filterByString(data, s) { return data.filter(e => e.id.includes(s) || e.taskname.includes(s)) .sort((a,b) => a.id.includes(s) && !b.id.includes(s) ? -1 : b.id.includes(s) && !a.id.includes(s) ? 1 :0); } console.log(filterByString(data, "ch")); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM