使用过滤器和映射而不是过滤器和循环的更智能方式

纳蒂姆

我想为以下示例创建一种更智能的编码方式。重要的是,在我们想要返回 filtersTest 之前,每个循环(对于 activeFilters)都需要完全完成。

const createFilters = async () => {
 const filtersTest = [] as any

 // Only create active filters by checking count.
 const activeFilters = getComponentFilter.value.filter(function(item) {
  if (item.items) {
    return item.items.some((obj) => obj.count)
  }
 });

 // Loop through the active filters and push arrays into the object.
 for(let i = 0 ; i < activeFilters.length; i++) {

  const options = await createFilterOptions(activeFilters[i].id, activeFilters[i].items);

  const array = {
    defaultValue: null,
    id: activeFilters[i].id,
    value: 'nee',
    label: activeFilters[i].label,
    options: options,
  }
  
  filtersTest.push(array)
 }

 return filtersTest;
}
特里科特

首先,应该清楚的createFilters是不会返回数组,而是最终将解析为该数组的承诺。

考虑到这一点,您可以使用Promise.all?.运算符、解构参数和对象文字中的速记属性名称来稍微减少代码:

const createFilters = () => Promise.all(
    getComponentFilter.value.filter(({items}) =>
        items?.some((obj) => obj.count)
    ).map(({id, label, items}) => 
        createFilterOptions(id, items).then(options => ({
            defaultValue: null,
            id,
            value: 'nee',
            label,
            options
        }))
    )
);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章