我正在尝试返回包含搜索字段中的值(任何对象中的任何字母匹配)的对象。
我想返回对象数组中的数组匹配的对象。
例子:
如果
搜索 = '狗'
然后我想回来
[{姓名:杰克,姓氏:DK,标签:['有趣','狗','猫']}]
或者如果
search = 'a' return [{name: Jake, last: DK, tags: ['fun','dog','cat']},{name: John, last: Hop, tags: ['boring','捕鼠器']}]
我的尝试:
this.state = {
search = '',
arr = [{name: Jake, last: DK, tags: ['fun','dog','cat']},
{name: John, last: Hop, tags: ['boring','mouse','trap']}]
}
//asuming the arr is stored in state
let filteredTag = this.state.arr.filter(obj => {
if (obj.tags !== undefined) {
return (
obj.tags.filter(tag => {
return tag.includes(this.state.search)
})
)
}
})
另外,我有
如果(obj.tags !== 未定义){
因为它是一个在单击按钮时出现的列表,并且在页面呈现时最初是未定义的。
过滤器的返回值应为真/假,具体取决于您是否需要特定元素。考虑到这一点,您需要进行以下更改。
let filteredTag = this.state.arr.filter(obj => {
if (obj.tags !== undefined) {
return (
obj.tags.filter(tag => {
return tag.includes(this.state.tagSearch)
}).length > 0 // since if tag has any element matching,filtered tags length can be checked
)
}
return false // since in undefined case,search condition is not met.
})
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句