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}});
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.
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.
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.
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 .
Lodash allows you to filter in nested data (including arrays) like this:
_.filter(modules, { submodules: [ { id: 2 } ]});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With