如何在对象的数组中搜索单个字符
const arr = [{ x: 1, tags: ["tag1", "taf", "ee", "xx"] },{ x: 3, tags: ["ta", "e", "xx"] }];
const fResult = arr.filter((res) => res.tags().includes("tag1"));
如果我们输入一个完整的tag1单词,而不仅仅是"t"或";ta"
如果你想匹配以它开头的值那么你需要使用some()
const filterIt = (arr, text) => arr.filter(
(res) =>
res.tags.some(
val => val.startsWith(text)
)
);
const arr = [{
x: 1,
tags: ["tag1", "taf", "ee", "xx"]
}, {
x: 3,
tags: ["ta", "e", "xx"]
}];
console.log("t", filterIt(arr, "t"));
console.log("ta", filterIt(arr, "ta"));
console.log("tag", filterIt(arr, "tag"));
终于想出了这个简单的解决办法
通过将标签数组转换为字符串,然后通过包含所有
来检查。const arr = [{ x: 1, tags: ["tag1", "taf", "ee", "xx"] },{ x: 3, tags: ["ta", "e", "xx"] }];
这是解const fResult = arr.filter((res) => res.tags.toString().includes("tag1"));