Lodash: how do I use filter when I have nested Object?

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);
});

Leave a Comment

tech