简体   繁体   English

根据条件数组递归过滤对象数组

[英]Recursively filter an array of objects according to an array of conditions

I have an array with objects that I want to filter according to an indefinite number of conditions passed as parameters. 我有一个包含对象的数组,我想根据作为参数传递的无限数量的条件进行过滤。

Here's how I filter the array a with a array of conditions in hide () 这是我如何使用hide()中的一系列条件过滤数组a

const statuses = [
  {
    id: 0,
    name: 'archived'
  },
  {
    id: 1,
    name: 'coming',
    hide: (...filterParam) => filterParam.every(rule => rule)
  }
];

const filteredStatuses = statuses.filter(element => {
  switch (element.id) {
    case 1:
      return !element.hide(this.isTopTabs());
    // other cases with others logic
    default:
      return true;
  }
});

Now if each object can have its own children object array like that: 现在,如果每个对象都有自己的子对象数组,那么:

const statuses = [
  {
    id: 'statuses',
    name: 'treeName',
    children: [
      {
        id: 1,
        name: 'inProgress',
        hide: (...filterParam) => filterParam.every(Boolean)
      },
      {
        id: 2,
        name: 'coming',
        checked: false,
        hide: (...filterParam) => filterParam.every(Boolean)
      }
    ]
  }
];

How I can recursively iterate the same way? 我如何以相同的方式递归迭代?

Do you have a better way to filter this array dynamically by avoiding the switch / case? 您是否有更好的方法通过避免切换/案例动态过滤此数组?

And finally how to type the rest parameters with a generic like that hide: <T>(...filterParam: Array<T>) => filterParam.every(Boolean) ? 最后如何使用类似于隐藏的泛型来键入其余参数: <T>(...filterParam: Array<T>) => filterParam.every(Boolean)

How I can recursively iterate the same way? 我如何以相同的方式递归迭代?

  const filterRecursively = elements => filterStatuses(elements).map(it => ({ ...it, children: it.children && filterRecursively(it.children) }));

Do you have a better way to filter this array dynamically by avoiding the switch / case? 您是否有更好的方法通过避免切换/案例动态过滤此数组?

Why? 为什么? Whats wrong with the switch case? switch盒有什么问题? Isn't it fancy enough? 不是很花哨吗?

And finally how to type the rest parameters with a generic like that hide: (...filterParam: Array) => filterParam.every(Boolean) ? 最后如何使用类似于隐藏的泛型来键入其余参数:(... filterParam:Array)=> filterParam.every(Boolean)?

  <T>(...filterParam: Array<T>) => boolean

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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