ArticleZip > Underscore Js Findwhere With Nested Property Value

Underscore Js Findwhere With Nested Property Value

Underscore.js makes working with arrays and objects in JavaScript a breeze. If you're looking to find objects within an array based on specific nested property values, the `_.findWhere` method is your go-to tool. In this article, we'll dive into how you can leverage the power of Underscore.js to use `findWhere` effectively, especially when dealing with nested property values.

### Understanding the `_.findWhere` Method

The `_.findWhere` method in Underscore.js provides a neat way to search through an array of objects and return the first object that matches the provided key-value pairs. The great thing about `_.findWhere` is that it allows you to specify nested properties to search within each object.

### Using `findWhere` with Nested Property Values

Let's say you have an array of objects representing different users, each with their own properties. To find a user with a specific nested property value, you can use `findWhere` like this:

Javascript

var users = [
  { id: 1, name: 'Alice', address: { city: 'New York' } },
  { id: 2, name: 'Bob', address: { city: 'San Francisco' } },
  { id: 3, name: 'Charlie', address: { city: 'Los Angeles' } }
];

var user = _.findWhere(users, { 'address': { 'city': 'San Francisco' } });

In this example, `user` will contain the object representing Bob because his address has a city property with the value 'San Francisco'.

### Dealing with Nested Properties

When working with nested properties, it's important to specify the complete path to the property you want to search for. In our example, `{ 'address': { 'city': 'San Francisco' } }` specifies that we are looking for an object where the address property contains an object with the city property set to 'San Francisco'.

### Handling Multiple Nested Property Values

You can also use `findWhere` to search for objects based on multiple nested properties. For instance, suppose you want to find a user with a specific city and postal code:

Javascript

var user = _.findWhere(users, { 'address': { 'city': 'Los Angeles', 'postalCode': '90001' } });

In this case, `user` will contain the object representing Charlie since his address matches both the city and postal code criteria.

### Conclusion

Using the `_.findWhere` method in Underscore.js allows you to efficiently search through arrays of objects with nested properties. By understanding how to specify nested property values, you can make your code more concise and readable while still achieving the desired search results. Next time you need to find objects based on nested property values, remember to reach for `findWhere` to simplify your code and get the job done effortlessly.