I have an array of an object like this
JavaScript
x
37
37
1
[
2
{
3
'a': 10,
4
elements: [
5
{
6
'prop': 'foo',
7
'val': 10
8
},
9
{
10
'prop': 'bar',
11
'val': 25
12
},
13
{
14
'prop': 'test',
15
'val': 51
16
}
17
]
18
},
19
{
20
'b': 50,
21
elements: [
22
{
23
'prop': 'foo',
24
'val': 30
25
},
26
{
27
'prop': 'bar',
28
'val': 15
29
},
30
{
31
'prop': 'test',
32
'val': 60
33
}
34
]
35
},
36
]
37
What I need is sum the property Val
when prop
is foo
.
So, I have to search through elements and get all objects where prop
is foo
. With this objects, I should sum the val
property.
I tried to use many combinations of _.find
, _.pick
and so on, but I don’t get the right result. Can someone help me?
Advertisement
Answer
Here’s a solution that flattens the elements and then filters the result to get the required elements before summing the val property:
JavaScript
1
7
1
var result = _.chain(data)
2
.map('elements') // pluck all elements from data
3
.flatten() // flatten the elements into a single array
4
.filter({prop: 'foo'}) // exatract elements with a prop of 'foo'
5
.sumBy('val') // sum all the val properties
6
.value()
7
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:
JavaScript
1
6
1
var result = _(data)
2
.map('elements')
3
.flatten()
4
.filter({prop: 'foo'})
5
.sumBy('val');
6