RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题 / 1588091
Accepted
MIA
MIA
Asked:2024-07-23 22:09:06 +0000 UTC2024-07-23 22:09:06 +0000 UTC 2024-07-23 22:09:06 +0000 UTC

ReactJS 如何按所需条件过滤数组?

  • 772

大家好!我正在尝试在项目中实现一个简单的搜索功能。项目 - 属性列表。我有一个包含这些元素的数组:

const selectedAttributesArray = [
{
attrType: "ЭЛЕМЕНТ",
code: "Teen",
id: 162,
links: [],
note: "string",
type: "protegrity",
},
{
attrType: "ЭЛЕМЕНТ",
code: "DE_unicode1",
id: 141,
links: [ 
{idElementConnect: 162, 
protectionFunc: 'DE1_string', 
unprotectionFunc: 'DE2_string', 
codeElementConnect: 'IK_HIVE'
},
],
note: "string",
type: "protegrity",
},
{
attrType: "ЭЛЕМЕНТ",
code: "R1_to_de",
id: 81,
links: [ 
{idElementConnect: 182, 
protectionFunc: 'ptyProtectStr', 
unprotectionFunc: 'ptyUnprotectStr', 
codeElementConnect: 'HIVE'}, 
{idElementConnect: null, 
protectionFunc: 'FUNCTION_FOR', 
unprotectionFunc: null, 
codeElementConnect: null}, 
{idElementConnect: 201, 
protectionFunc: 'ptyProtectStr', 
unprotectionFunc: 'ptyUnprotectStr', 
codeElementConnect: 'SPARK'},
],
note: "string1",
type: "protegrity",
}
]

要查找数组元素,需要有一个具有单独 searchValue 状态的输入(该状态位于父组件中):

export const SearchWidget = ({ searchValue, handleSearchQuery }) => {
    
  return (
    <div className={styles.mainContainer}>
        <Input
        placeholder='Найти атрибут...'
        value={searchValue}
        onChange={(e: string) => handleSearchQuery(e)} 
        />
    </div>
  )
}

最后,使用该函数过滤数组,以便可以在渲染期间映射其中的数据:

    export const DataResultCards = ({ selectedAttributesArray, searchValue, handleOpenSideBar }) => {
  
  const filteredAttributeList = selectedAttributesArray?.filter(attribute =>
    new RegExp(`${searchValue.toLowerCase().replace(/%/g, '.')}`).test(attribute.code.toLowerCase()),
  );

  return (
    <>
      {filteredAttributeList.length > 0 ? (
        filteredAttributeList?.map(attribute => {
          return <DataResultCard attribute={attribute} />;
        })
      ) : (
        <div>Ничего не найдено</div>
      )}
    </>
  );
};

应该如何进行搜索 例如:

  1. 当我在搜索中输入“ de ”时,我得到两个对象:属性卡“ DE unicode1”和“R1_to de ”(通过属性名称找到)
  2. 如果我在搜索中输入“ hiv ”,我将在屏幕上看到卡片“DE_unicode1”(它有 codeElementConnect: 'IK_HIVE ')和“R1_to_de”(它有 codeElementConnect: ' HIVE ')。
  3. 当您输入“ Str ”时,结果是相同的,因为它们具有protectionFunc:'DE1_string '和protectionFunc:'ptyProtect Str '。

个人属性卡代码:

export const DataResultCard = ({ attribute, handleOpenSideBar }) => {
  return (
    <Card
      style={{ width: 804, minHeight: 180, marginBottom: '5px' }}
    >
<Tag classes={{ tag: styles.typeTag }}>{attribute.attrType}</Tag>
        {attribute.links.length > 0
          ? attribute.links?.map(link => {
              if (link.codeElementConnect === null) {
                return null;
              } else {
                return (
                  <div onClick={() => handleOpenSideBar(link)}>
                    <Tag classes={{ tag: styles.connectedAttrTag }}>{link.codeElementConnect}</Tag>
                  </div>
                );
              }
            })
          : null}
<Text kind="h4b">{attribute.code}</Text>
<Text kind="textSb">Функции шифрования: </Text>
              {attribute.links?.map(link => {
                return (
                  <ul>
                    <li>
                      <ListEncryptionFunction link={link} attribute={attribute} />
                    </li>
                  </ul>
                );
              })}
</Card>
  );
};

我尝试重写过滤器,以便属性中的链接数组也可以用于通过链接名称查找元素:

 const filteredAttributeList = selectedAttributesArray?.filter((attribute) => {
        attribute.links?.map((link) => {
          if (link.codeElementConnect !== null) {
            new RegExp(`${searchValue.toLowerCase().replace(/%/g, '.')}`).test(link.codeElementConnect.toLowerCase()),
          } else {
            new RegExp(`${searchValue.toLowerCase().replace(/%/g, '.')}`).test(attribute.code.toLowerCase()),
          }
        } 
          )
      }
    );

但搜索并非如此。如何设置具有多个条件的过滤器以通过链接名称查找元素?

reactjs
  • 2 2 个回答
  • 56 Views

2 个回答

  • Voted
  1. ksa
    2024-07-24T22:16:53Z2024-07-24T22:16:53Z

    应该如何进行搜索 例如:当我在搜索中输入“de”时,我会得到两个对象:属性卡“DEunicode1”和“R1_tode”(通过属性名称找到)如果我输入“hiv” ”进入搜索,我将在屏幕上获得卡片“DE_unicode1”(它具有 codeElementConnect:'IK_HIVE')和“R1_to_de”(它具有 codeElementConnect:'HIVE')。当您输入“Str”时,结果是相同的,因为它们具有protectionFunc:'DE1_string'和protectionFunc:'ptyProtectStr'。

    我会建议这个过滤选项......

    const arr = [
        {
            attrType: "ЭЛЕМЕНТ",
            code: "Teen",
            id: 162,
            links: [],
            note: "string",
            type: "protegrity",
        },
        {
            attrType: "ЭЛЕМЕНТ",
            code: "DE_unicode1",
            id: 141,
            links: [ 
                {
                    idElementConnect: 162, 
                    protectionFunc: 'DE1_string', 
                    unprotectionFunc: 'DE2_string', 
                    codeElementConnect: 'IK_HIVE'
                },
            ],
            note: "string",
            type: "protegrity",
        },
        {
            attrType: "ЭЛЕМЕНТ",
            code: "R1_to_de",
            id: 81,
            links: [ 
                {
                    idElementConnect: 182, 
                    protectionFunc: 'ptyProtectStr', 
                    unprotectionFunc: 'ptyUnprotectStr', 
                    codeElementConnect: 'HIVE'
                }, 
                {
                    idElementConnect: null, 
                    protectionFunc: 'FUNCTION_FOR', 
                    unprotectionFunc: null, 
                    codeElementConnect: null
                }, 
                {
                    idElementConnect: 201, 
                    protectionFunc: 'ptyProtectStr', 
                    unprotectionFunc: 'ptyUnprotectStr', 
                    codeElementConnect: 'SPARK'
                },
            ],
            note: "string1",
            type: "protegrity",
        }
    ]
    const a = ['de', 'hiv', 'Str']
    a.forEach(v => console.log(v, test(arr, v).map(o => o.code)))
    
    //
    function test(arr, txt = '') {
        const r = new RegExp(txt, 'i')
        const fn1 = v => r.test(v)
        const fn2 = o => Object.values(o).some(fn1)
        const fn3 = obj => r.test(obj.code) || obj.links.some(fn2)
        return arr.filter(fn3)
    }

    • 1
  2. Best Answer
    Oliver Patterson
    2024-07-24T21:31:35Z2024-07-24T21:31:35Z

    如果我正确理解了问题,并且您需要按 或code中的对象中的值进行搜索links,那么此代码将是正确的。

    const selectedAttributesArray = [
        {
            attrType: "ЭЛЕМЕНТ",
            code: "Teen",
            id: 162,
            links: [],
            note: "string",
            type: "protegrity",
        },
        {
            attrType: "ЭЛЕМЕНТ",
            code: "DE_unicode1",
            id: 141,
            links: [
                {
                    idElementConnect: 162,
                    protectionFunc: 'DE1_string',
                    unprotectionFunc: 'DE2_string',
                    codeElementConnect: 'IK_HIVE'
                },
            ],
            note: "string",
            type: "protegrity",
        },
        {
            attrType: "ЭЛЕМЕНТ",
            code: "R1_to_de",
            id: 81,
            links: [
                {
                    idElementConnect: 182,
                    protectionFunc: 'ptyProtectStr',
                    unprotectionFunc: 'ptyUnprotectStr',
                    codeElementConnect: 'HIVE'
                },
                {
                    idElementConnect: null,
                    protectionFunc: 'FUNCTION_FOR',
                    unprotectionFunc: null,
                    codeElementConnect: null
                },
                {
                    idElementConnect: 201,
                    protectionFunc: 'ptyProtectStr',
                    unprotectionFunc: 'ptyUnprotectStr',
                    codeElementConnect: 'SPARK'
                },
            ],
            note: "string1",
            type: "protegrity",
        }
    ];
    
    const filteredAttributeList = useMemo(() =>
    {
        const filtered = selectedAttributesArray.filter((attribute) =>
        {
            const searchValueReg = new RegExp(searchValue.replace(/%/g, '.'), "i");
    
            if (searchValueReg.test(attribute.code))
            {
                    return true;
            }
            
            return attribute.links.some((link) => 
            {
                return Object.values(link).filter((linkValue) =>
                {
                    return searchValueReg.test(linkValue);
                }).length > 0
            });
        });
    
        return filtered;
    }, [ searchValue, selectedAttributesArray ]);
    
    • 0

相关问题

  • 如果图像在道具中,如何使背景图像做出反应?

  • 项目未显示

  • 引发错误:InvalidTokenError: Invalid token specified: Cannot read property 'replace' of undefined

  • 如何在没有 node.js 的情况下运行 react.js 应用程序

  • 如何从 React Native 中的导航堆栈中清除上一个屏幕?

  • 为什么渲染后会触发 Click 事件?

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5