我有以下脚本,我需要返回以下结果:
{
text: 'i love apples'
}, {
text: 'i eat my apple'
}, {
text: 'no apples on the table'
}
使用以下脚本我收到错误。
我做错了什么,如何修复它(另外一种不使用.match的解决方案也可以。)
注意:搜索值可能不同,因此脚本应该可以重复使用。
let data = [{
text: 'i love apples'
}, {
text: 'i eat my apple'
}, {
text: 'no apples on the table'
},{
text: 'i love oranges'
}];
let search = 'apple'
let filter = data.filter(item=>{ return item.match(search)})
console.log(filter)

答案 0 :(得分:3)
使用includes
代替并确保在迭代中引用该属性。
let data = [{
text: 'i love apples'
}, {
text: 'i eat my apple'
}, {
text: 'no apples on the table'
}, {
text: 'i love oranges'
}];
let search = 'apple';
let filter = data.filter(item => item.text.includes(search))
console.log(filter)
答案 1 :(得分:1)
你就在那里,使用item.text.match
。其中item是数据数组的迭代器。
let data = [{
text: 'i love apples'
}, {
text: 'i eat my apple'
}, {
text: 'no apples on the table'
},{
text: 'i love oranges'
}];
let search = 'apple'
let filter = data.filter(item=>{ return item.text.match(search)})
console.log(filter)
答案 2 :(得分:1)
我觉得你唯一缺少的是item.text
,匹配是string
而不是object
上的一项功能,你想要更深层次以匹配内容。< / p>
let data = [{
text: 'i love apples'
}, {
text: 'i eat my apple'
}, {
text: 'no apples on the table'
},{
text: 'i love oranges'
}];
let search = 'apple'
let filter = data.filter((item)=>{ return item.text.match(search)})
console.log(filter)