I'm trying to do something similar to the autocomplete widget in jQuery UI with userscore. I've tried using _.where(), but this only works if there's a complete match.
This works:
var people = [
    { id: 1, name: "Jimmy" },
    { id: 2, name: "Johnny" },
    { id: 3, name: "Susan" },
    { id: 4, name: "Tim" },
    { id: 5, name: "Betty" },
    { id: 6, name: "Ralph" }
];
var filteredPeople = _.where(people, { name: "Jimmy" });
But what I would like is something like this:
var filteredPeople = _.where(people, { name: "im" });   //Should return "Jimmy" and "Tim"
Is using ._where not the correct approach? If not, what would be a better way to approach this?
Is using ._where not the correct approach?
Yes. _.where returns "values that contain all of the key-value pairs listed". This exact match is not what you want.
What would be a better way to approach this?
Use the more general _.filter function:
var filteredPeople = _.filter(people, function(person) {
    return person.name.indexOf("im") > -1;
});
Of course, you can use something different from indexOf. If you wanted to use regular expressions, it might look like:
return /im/.test(person.name);
                        in 2017 you can do:
lodash:
_.filter(people, p => _.includes(p.name, 'im'))
es6:
people.filter(p => p.name.includes('im'))
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With