Lodash: how to use a filter when I have a nested object?

Consider this example. I am using lodash

'data': [ { 'category': { 'uri': '/categories/0b092e7c-4d2c-4eba-8c4e-80937c9e483d', 'parent': 'Food', 'name': 'Costco' }, 'amount': '15.0', 'debit': true }, { 'category': { 'uri': '/categories/d6c10cd2-e285-4829-ad8d-c1dc1fdeea2e', 'parent': 'Food', 'name': 'India Bazaar' }, 'amount': '10.0', 'debit': true }, { 'category': { 'uri': '/categories/d6c10cd2-e285-4829-ad8d-c1dc1fdeea2e', 'parent': 'Food', 'name': 'Sprouts' }, 'amount': '11.1', 'debit': true }, 

When i do

 _.filter(summary.data, {'debit': true}) 

I return all objects.

what I want?

I need all the objects where category.parent == 'Food' , how can I do this?

I tried

 _.filter(summary.data, {'category.parent': 'Food'}) 

and received

 [] 
+50
javascript lodash
Jun 13 '13 at 21:00
source share
5 answers
 _.filter(summary.data, function(item){ return item.category.parent === 'Food'; }); 
+35
Jun 13 '13 at 22:27
source share

lodash allows you to define nested objects:

 _.filter(summary.data, {category: {parent: 'Food'}}); 

Starting with version v3.7.0, lodash also allows you to specify object keys in lines:

 _.filter(summary.data, ['category.parent', 'Food']); 

Sample code in JSFiddle: https://jsfiddle.net/6qLze9ub/

lodash also supports array nesting; if you want to filter one of the elements of the array (for example, if the category is an array):

 _.filter(summary.data, {category: [{parent: 'Food'}] }); 

If you really need some sort of selective comparison, then when to pass the function:

 _.filter(summary.data, function(item) { return _.includes(otherArray, item.category.parent); }); 
+108
Apr 25 '14 at 18:30
source share

starting with v3.7.0 , you can do it like this:

 _.filter(summary.data, 'category.parent', 'Food') 
+11
Oct 12 '15 at 13:20
source share
 _.where(summary.data, {category: {parent: 'Food'}}); 

Gotta do the trick too

+2
Dec 17 '14 at 2:02
source share

In lodash 4.x you need to do:

 _.filter(summary.data, ['category.parent', 'Food']) 

(note that the array wraps the second argument).

This is equivalent to calling:

 _.filter(summary.data, _.matchesProperty('category.parent', 'Food')) 

Here are the docs for _.matchesProperty :

 // The `_.matchesProperty` iteratee shorthand. _.filter(users, ['active', false]); // => objects for ['fred'] 
+1
Nov 15 '16 at 20:21
source share



All Articles