不能在js中使用string.match

时间:2017-09-19 19:07:02

标签: javascript

我有以下脚本,我需要返回以下结果:

{
      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)




3 个答案:

答案 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)