javascript 如何检查Angular [副本]中的多个空值

velaa5lx  于 2022-12-17  发布在  Java
关注(0)|答案(1)|浏览(395)

此问题在此处已有答案

How to filter array of objects using customized input as filters(1个答案)
9小时前关门了。
我有3 ngModel在我的用户界面是绑定在我的Angular 应用程序。他们都是由用户选择使用多选下拉菜单。

country = ["India", "US"]
state = ["Delhi", "MP","UP"]
city = ["gzb","xyz"]

我有一个自定义筛选器,必须根据这些响应筛选数据

filter = {
country: this.country,
state: this.state,
city: this.city
}

result = data.filter(e =>
Object.entries(filters).every(([key,vals])=>vals.includes(e[key])))

有一个场景,只有国家数组,其他2个都是空的。这里我的过滤器将失败。如何检查null
测试数据

data=[{
"name":"hello",
"gender":"male",
"country":"India",
"state":"Delhi",
"city":"gzb"
}]
hm2xizp9

hm2xizp91#

你必须检查过滤器元件的长度。
如果filter中特定节点的长度为零,那么检查该filter节点就没有意义,只需在这种情况下返回true。

工作小提琴

const country = ["India", "US"];
// const state = ["Delhi", "MP", "UP"];
const state = [];
const city = ["gzb", "xyz"];
const filter = {
  country,
  state,
  city,
};
const data = [
  {
    name: "hello",
    gender: "male",
    country: "India",
    state: "Delhi",
    city: "gzb",
  },
];
const result = data.filter((e) =>
  Object.entries(filter).every(([key, vals]) => vals.length > 0 ? vals.includes(e[key]) : true)
);
console.log(result);

相关问题