如何使用Typescript / Javascript / Angular 4过滤JSON数据?

时间:2018-01-21 05:03:20

标签: javascript angular typescript

我有像这样的json数据

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'}
}]

现在我需要过滤此数据并返回匹配值(就像自动完成一样)。例如,当我获得值 CH 时,首先我需要检查 ID ,然后检查任务名称。所以返回值应该是这样的。 必须订购ID匹配top,然后匹配taksname。

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

如果我得到CHE值,那么我需要像这样返回值

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

有人可以告诉我如何使用打字稿进行过滤吗?

Tried few of this answer,但没有运气。

1 个答案:

答案 0 :(得分:3)

试试此代码

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