Fuse.js: Fuzzy search in Array like object

marcobiedermann picture marcobiedermann · Nov 15, 2016 · Viewed 8k times · Source

I would like to perform a fuzzy search on an Object with a flat hierarchy. On the demo page of Fuse.js you have to specify a key / keys to look for in the Object. Unfortunately I do not have a specific identifier.

Fuse.js Demo:

var books = [{
  title: "Old Man's War",
  author: {
    firstName: "John",
    lastName: "Scalzi"
  }
}];
var fuse = new Fuse(books, { keys: ["title", "author.firstName"] });

My Setup:

const data = {
  "100": "https://assets-cdn.github.com/images/icons/emoji/unicode/1f4af.png?v6",
  "1234": "https://assets-cdn.github.com/images/icons/emoji/unicode/1f522.png?v6",
  "+1": "https://assets-cdn.github.com/images/icons/emoji/unicode/1f44d.png?v6",
  "-1": "https://assets-cdn.github.com/images/icons/emoji/unicode/1f44e.png?v6"
};

const fuse = new Fuse(data, { keys: ??? });
fuse.search('+1'); // should return "https://assets-cdn.github.com/images/icons/emoji/unicode/1f44d.png?v6",

Answer

Gershon Papi picture Gershon Papi · Nov 15, 2016

You could get the keys for your dynamic object using the Object.keys() function. If you wish to support older browsers too you can find a polyfill implementation here (under Polyfill).

Then, you could supply Fuse, the keys like this: Object.keys(myobject).

EDIT:

In order to transform the object itself you could do something similar to what Jordan has suggested:

var newData = Object.keys(data).map(function(key) {
  return { id: key, link: data[key]};
}) 

And then the keys array is ['id'] and you should search by the id.