Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lodash: how do I use filter when I have 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 get all the objects back.

what I want?

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

I tried

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

and got

[] 
like image 559
daydreamer Avatar asked Jun 13 '13 21:06

daydreamer


People also ask

How do you filter nested array of objects in Lodash?

If you need to search for a nested object, you can use Lodash's . find() function.It takes three arguments: collection : which can be either an array or object. predicate : the callback function that Lodash calls on every element in the array.

What does Lodash filter return?

Lodash's `filter()` Function Apr 6, 2020. Given an array arr , Lodash's filter() function returns an array containing all the elements in arr for which the function returned a truthy value. const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]; _.filter(arr, isEven); // [2, 4, 6, 8] function isEven(v) { return v % 2 === 0; }


2 Answers

lodash allows nested object definitions:

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

As of v3.7.0, lodash also allows specifying object keys in strings:

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

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

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

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

If you really need some custom comparison, that's when to pass a function:

_.filter(summary.data, function(item) {   return _.includes(otherArray, item.category.parent); }); 
like image 137
Akrikos Avatar answered Oct 13 '22 10:10

Akrikos


_.filter(summary.data, function(item){   return item.category.parent === 'Food'; }); 
like image 30
idbehold Avatar answered Oct 13 '22 10:10

idbehold