Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find object by match property in nested array

Tags:

lodash

I'm not seeing a way to find objects when my condition would involve a nested array.

var modules = [{     name: 'Module1',     submodules: [{         name: 'Submodule1',         id: 1       }, {         name: 'Submodule2',         id: 2       }     ]   }, {     name: 'Module2',     submodules: [{         name: 'Submodule1',         id: 3       }, {         name: 'Submodule2',         id: 4       }     ]   } ]; 

This won't work because submodules is an array, not an object. Is there any shorthand that would make this work? I'm trying to avoid iterating the array manually.

_.where(modules, {submodules:{id:3}}); 
like image 814
helion3 Avatar asked May 07 '15 17:05

helion3


People also ask

How do you access the properties of a nested object?

A nested data structure is an array or object which refers to other arrays or objects, i.e. its values are arrays or objects. Such structures can be accessed by consecutively applying dot or bracket notation.

How do I compare two nested arrays?

equals() Method. Java Arrays class provides the equals() method to compare two arrays. It iterates over each value of an array and compares the elements using the equals() method.

What is nested type in Elasticsearch?

The nested type is a specialised version of the object data type that allows arrays of objects to be indexed in a way that they can be queried independently of each other.

What is a nested field?

When a packed class contains an instance field that is a packed type, the data for that field is packed directly into the containing class. The field is known as a nested field .


2 Answers

Lodash allows you to filter in nested data (including arrays) like this:

_.filter(modules, { submodules: [ { id: 2 } ]});

like image 181
martinoss Avatar answered Sep 28 '22 02:09

martinoss


Here's what I came up with:

_.find(modules, _.flow(     _.property('submodules'),     _.partialRight(_.some, { id: 2 }) )); // → { name: 'Module1', ... } 

Using flow(), you can construct a callback function that does what you need. When call, the data flows through each function. The first thing you want is the submodules property, and you can get that using the property() function.

The the submodules array is then fed into some(), which returns true if it contains the submodule you're after, in this case, ID 2.

Replace find() with filter() if you're looking for multiple modules, and not just the first one found.

like image 20
Adam Boduch Avatar answered Sep 28 '22 03:09

Adam Boduch