Fuse.js在字符串数组中搜索

时间:2019-12-04 14:42:44

标签: javascript fuse.js

我试图在我的应用中实现fuse.js,在我的应用中我有没有任何键的字符串数组。

['Kelly', 'Creed', 'Stanley', 'Oscar', 'Michael', 'Jim', 'Darryl', 'Phyllis', 'Pam', 'Dwight', 'Angela', 'Andy', 'William', 'Ryan', 'Toby', 'Bob']

当我尝试配置fuse.js时,由于密钥未指定,我没有任何结果。

var options = {
  shouldSort: true,
  threshold: 0.6,
  location: 0,
  distance: 100,
  maxPatternLength: 32,
  minMatchCharLength: 1,
  keys: [
    "title",
    "author.firstName"
  ]
};
var fuse = new Fuse(list, options); // "list" is the item array
var result = fuse.search("");

是否可以在纯数组上执行模糊搜索,还是我需要将所有内容都转换为对象?

1 个答案:

答案 0 :(得分:1)

可以对字符串数组进行搜索。您无需在选项对象中指定keys属性。

这是一个例子:

const list = ['Kelly', 'Creed', 'Stanley'];

// your options can be anything you want, but don't include
// the keys property
let options = {
  shouldSort: true,
  threshold: 0.6,
  location: 0,
  distance: 100,
  maxPatternLength: 32,
  minMatchCharLength: 1,
  // don't include the keys property
};

const fuse = new Fuse(list, options);

let result = fuse.search('Kelly');
// result will be:
// {"item":"Kelly","refIndex":0}
// here, refIndex is the index of the element in list