Lodash - Find deep in array of object
Here's a solution that flattens the elements and then filters the result to get the required elements before summing the val property:
var result = _.chain(data)
.map('elements') // pluck all elements from data
.flatten() // flatten the elements into a single array
.filter({prop: 'foo'}) // exatract elements with a prop of 'foo'
.sumBy('val') // sum all the val properties
.value()
Chaining is a way of applying a sequence of operations to some data before returning a value. The above example uses explicit chaining but could be (maybe should be) written using implicit chaining:
var result = _(data)
.map('elements')
.flatten()
.filter({prop: 'foo'})
.sumBy('val');
I've created library that you can use: https://github.com/dominik791/obj-traverse
findAll()
method should solve your problem. The first parameter is a root object, not array, so you should create it at first:
var rootObj = {
name: 'rootObject',
elements: [
{
'a': 10,
elements: [ ... ]
},
{
'b': 50,
elements: [ ... ]
}
]
};
Then use findAll()
method:
var matchingObjects = findAll( rootObj, 'elements', { 'prop': 'foo' } );
matchingObjects
variable stores all objects with prop
equal to foo
. And at the end calculate your sum:
var sum = 0;
matchingObjects.forEach(function(obj) {
sum += obj.val;
});