javascript - 在某些情况下从数组中删除对象

标签 javascript reactjs

我需要按某些情况的顺序更新过滤器。

在某些数据条件下,我需要从数组中删除 1 项。

这是代码

    useEffect(() => {
        let canceled = false;
        const filters = [
            new CheckFilterBuilder('badges', 'Badges'),
            new CategoryFilterBuilder('category', 'Categories'),
            new RangeFilterBuilder('price', 'Price'),
            new CheckFilterBuilder('brand', 'Brand'),
        ];
        console.log(filters);

        dispatch({ type: 'FETCH_PRODUCTS_LIST' });
        shopApi.getProductsList(
            state.options,
            { ...state.filters, category: categorySlug }, filters,
        ).then((productsList) => {
            if (canceled) {
                return;
            }

            dispatch({ type: 'FETCH_PRODUCTS_LIST_SUCCESS', productsList });
        });

        return () => {
            canceled = true;
        };
    }, [dispatch, categorySlug, state.options, state.filters]);

我尝试了使用 if() 语句的解决方案,但无法将其放入我想要的删除项目中

new RangeFilterBuilder('price', 'Price'),

因为它不接受 if() 或其他任何东西,我无法做到这一点。

最佳答案

您可以通过创建一个空的过滤器(或已包含已知的过滤器)并根据条件添加(推送)其他过滤器来实现此目的

const filters = [new CheckFilterBuilder('badges', 'Badges')];

if (condition === true) {filters.push(new CategoryFilterBuilder('category', 'Categories'))}
if (condition === true) {filters.push(new RangeFilterBuilder('price', 'Price'))}
if (condition === true) {filters.push(new CheckFilterBuilder('brand', 'Brand'))}

关于javascript - 在某些情况下从数组中删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68089395/

相关文章:

javascript - 在 Javascript 中添加数组对象中对象的值

javascript - 不可变状态是 ReactJs 中的功能特性?

reactjs - 在 Gatsby 中将 HTTP 流量重定向到 HTTPS

javascript - 在 React 组件的渲染函数中返回 DOM 元素

javascript - crypto-js 如何隐藏类方法?

javascript - 在 Javascript 中 chop 一个字符串,混淆最后两个测试字符串

javascript - 如何根据另一个对象数组过滤一个对象数组?

ios - 在 iOS 应用程序中使用 rct 桥来表示 react native 中的 TableView

javascript - Bootstrap 确认不尊重选项

javascript - 组件中的空状态(react redux)