我正在尝试返回包含搜索字段中的值(任何对象中匹配的任何字母)的对象。
我想返回对象数组中的数组匹配的对象。
示例:
如果
search = 'dog'
那我想回来
[{name: Jake, last: DK, tags: ['fun','dog','cat']}]
或者如果
search = 'a' return [{name: Jake, last: DK, tags: ['fun','dog','cat']},{name: John, last: Hop, tags: ['boring','mouse','trap']}]
我的尝试:
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)
})
)
}
})
另外,我还有
if (obj.tags !== undefined) {
因为它是单击按钮时出现的列表,并且在页面呈现时最初未定义。
最佳答案
过滤器的返回值应该是 true/false,具体取决于您是否想要特定元素。考虑到这一点,您需要进行以下更改。
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.
})
关于javascript - 在对象数组中查找数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53436367/