我有像这样的json数据
jsonList= [
{name:'chennai', code:'maa'}
{name:'delhi', code:'del'}
....
....
....
{name:'salem', code:'che'}
{name:'bengaluru',code:'blr'}
}]
现在我需要根据键(名称,代码)过滤此数据并返回匹配值。例如,如果给出 CHE ,首先我需要检查CODE,如果没有值匹配,那么我需要检查NAME
{name:'salem', id:'che'},
{name:'chennai', id:'maa'}
我尝试了以下代码,但它不起作用。每次只检查NAME
public filterJson(text){
this.filteredOptions = this.jsonList.filter(
e => (
e.code.toLowerCase().indexOf(text.toString().toLowerCase()) !== -1) ||
e.name.toLowerCase().indexOf(text.toString().toLowerCase()) !== -1)
).slice(0, 9);
}
并尝试使用0
public filterJson(text){
this.filteredOptions = this.jsonList.filter(
e => (
e.code.toLowerCase().indexOf(text.toString().toLowerCase()) === 0) ||
e.name.toLowerCase().indexOf(text.toString().toLowerCase()) === 0)
).slice(0, 9);
}
答案 0 :(得分:1)
以下适用于我(修复多个语法错误,一个附加变量,无逻辑更改)
var jsonList= [
{name:'chennai', code:'maa'}, // added commas
{name:'delhi', code:'del'},
{name:'salem', code:'che'},
{name:'bengaluru',code:'blr'},
/* removed redundant closing brace */ ];
function filterJson(text) {
const lcText = text.toString().toLowerCase(); // calculate this once
return jsonList.filter(
e => (
// Added initial opening brace
(e.code.toLowerCase().indexOf(lcText) === 0) ||
(e.name.toLowerCase().indexOf(lcText) === 0)
)// added closing brace
).slice(0, 9);
}
JSON.stringify(filterJson(" che"))
"[{"name":"chennai","code":"maa"},{"name":"salem","code":"che"}]"
您确定您的代码已编译完成吗?这是TypeScript的主要优点之一,它会在编译时检查您的语法。
答案 1 :(得分:1)
已经由@Motti给出的答案:)只是想更新如何排序,这可能对某人有所帮助。
this.jsonList.filter(
e => (
(e.code.toLowerCase().indexOf(text) === 0) ||
(e.name.toLowerCase().indexOf(text) === 0)
)).sort(
(a, b) =>
(
(a.code.toLowerCase().indexOf(text) === 0) ? -1 :
(b.code.toLowerCase().indexOf(text) === 0) ? 1 : 0
)
)
.slice(0, 10);