marcobiedermann
marcobiedermann

Reputation: 4915

Fuse.js: Fuzzy search in Array like object

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",

Upvotes: 3

Views: 10596

Answers (2)

Jordan Enev
Jordan Enev

Reputation: 18644

First parse your data:

const data = JSON.parse(json);

Then one way to do it (but for sure it would be slower than second suggestions, because of all of the keys are included in the search):

const fuse = new Fuse(data, { keys: data.keys() });

Or you can change your data structure dynamically:

let structuredData = [];

for (key in data)
    structuredData.push({
        "id": key,
        "url": structuredData[key]
    });

const fuse = new Fuse(structuredData, { keys: ["id"] });

Upvotes: 5

Gershon Papi
Gershon Papi

Reputation: 5106

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.

Upvotes: 6

Related Questions