Ruslan Konev
Ruslan Konev

Reputation: 11

How search some object in other case-insensitive in JavaScript? Like _.where() only case-insensitive

I need find some object by two properties and his value in collections, like in loDash:

_.where(collection, searchObject)

only case-insensitive.

How can I do that?

has object:

[{
    "city": "New York, US",
    "name": "John",
    "address": "Allen Street, 0123",
},{
    "city": "New York, US",
    "name": "Dale",
    "address": "Barrow Street, 3210",
}];

I need pass a param like a

{ 
    "city": 'new york, US'
    "address": "Barrow street, 3210"
} 

and find a second object as result.

This logic provide a _.where function in loDash or Underscore, but his search will not case-insensitive.

Upvotes: 1

Views: 59

Answers (1)

Adam Boduch
Adam Boduch

Reputation: 11211

If you need case insensitivity, where-style syntax won't work. Your best bet is to setup a generic function that builds and returns iteratee functions that can be used by filter(). Here's an example that uses regular expressions with the insensitive flag set:

function filterInsensitive(property, regexp) {
  return _.flow(
    _.identity,
    _.partialRight(_.get, property),
    _.method('match', regexp)
  );
}

This function is generic enough that it can be used with any collection, for any property value, using any regular expression as the filter. Here's how you would use it with your data.

_(myColl)
  .filter(filterInsensitive('city', /NEW YORK, US/i))
  .filter(filterInsensitive('address', /barrow street, 3210/i))
  .value();

Upvotes: 1

Related Questions