gpt4 book ai didi

javascript - 如何从匹配特定字符的对象数组中提取属性(包含查询)

转载 作者:行者123 更新时间:2023-11-29 20:37:37 24 4
gpt4 key购买 nike

我有任何具有属性 id 和 title 的对象数组。我想获取包含用户在 title 属性中输入的字符的所有对象的 id

>[{ID: 3, Title: "License 1"},
{ID: 4, Title: "License 2"},
{ID: 36, Title: "License 3"},
{ID: 37, Title: "License 4"},
{ID: 38, Title: "sense 4"}]

如果用户输入 lic,这是示例数组,它应该返回我 n 数组a=[3,4,36,37]

最佳答案

您可以使用 regular expressions以及Array methods匹配字符搜索:

const arr = [{ ID: 3, Title: 'License 1' }, ... ];
const query = 'lic';
const reg = new RegExp('.*' + query + '.*', 'gi');

arr.filter((x) => x.ID.match(reg)).map((x) => x.ID);
// [3, 4, 36, 37, ...]

关于javascript - 如何从匹配特定字符的对象数组中提取属性(包含查询),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56366962/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com