krisk / Fuse

Lightweight fuzzy-search, in JavaScript
https://fusejs.io/
Apache License 2.0
18.05k stars 766 forks source link

fuse.js return specific item from nested json object #458

Closed ibraheemdev closed 4 years ago

ibraheemdev commented 4 years ago

I am using fuse.js to fuzzy search a json dataset that looks like this:

const dataSet = [
    {
      title: "a list",
      cards: [
        {
          title: "a card",
        },
        {
          title: "another card",
        },
        {
          title: "a third card",
        },
      ],
    },
...
];

When I perform a search for a card title:

const fuse = new Fuse(dataSet, { keys: ['cards.title']})
console.log(fuse.search("a third card"))

the list that contains the card is returned

{
   title: "a list",
   cards: [
      {id: 1, title: "a card"},
      ...
   ]
}

I want the data to return the specific card that has the title "a third card". Is there any way I can do this?

I looked into the docs, and found a getFn option that might do the job, but I couldn't get it to work. I also know that I can achieve this by flattening my object, but I don't want to do that as it adds complexity for my use case.

krisk commented 4 years ago

For future reference, these types of questions would be better if asked on Stack Overflow, that way everyone can benefit, but also the question is bound to get wider reach (and thus an answer from someone other than me 😄 ).

Sounds like what you could do is set the option includeMatches to true. This would also give you the exact item that was matched in the nested sub-array.

ibraheemdev commented 4 years ago

Oh, ok thanks, that worked perfectly! p.s: I did ask on stack overflow here but did not get any response, so I came here 😀

krisk commented 4 years ago

Guess I'll answer your Q there as well 😄

evanjmg commented 2 years ago

This doesn't work for the example above