Lodash - 深入查找对象数组 [英] Lodash - Find deep in array of object
问题描述
我有一个像这样的对象数组
I have an array of an object like this
[
{
'a': 10,
elements: [
{
'prop': 'foo',
'val': 10
},
{
'prop': 'bar',
'val': 25
},
{
'prop': 'test',
'val': 51
}
]
},
{
'b': 50,
elements: [
{
'prop': 'foo',
'val': 30
},
{
'prop': 'bar',
'val': 15
},
{
'prop': 'test',
'val': 60
}
]
},
]
Wh我需要的是当 prop
是 foo
Val >。
所以,我必须搜索元素并获取所有 prop
的对象是 foo
。有了这个对象,我应该总结 val
属性。
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.
我试图使用<$ c $的许多组合c> _。找到, _。选择
等等,但我得不到正确的结果。有人可以帮帮我吗?
I tried to use many combinations of _.find
, _.pick
and so on, but I don't get the right result. Can someone help me?
推荐答案
这是 展平 元素,然后 过滤 结果,以便在 汇总 val属性:
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');
这篇关于Lodash - 深入查找对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!