javascript Lodash:嵌套对象时如何使用过滤器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17096988/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Lodash: how do I use filter when I have nested Object?
提问by daydreamer
Consider this example. I am using Lodash
考虑这个例子。我正在使用Lodash
'data': [
{
'category': {
'uri': '/categories/0b092e7c-4d2c-4eba-8c4e-80937c9e483d',
'parent': 'Food',
'name': 'Costco'
},
'amount': '15.0',
'debit': true
},
{
'category': {
'uri': '/categories/d6c10cd2-e285-4829-ad8d-c1dc1fdeea2e',
'parent': 'Food',
'name': 'India Bazaar'
},
'amount': '10.0',
'debit': true
},
{
'category': {
'uri': '/categories/d6c10cd2-e285-4829-ad8d-c1dc1fdeea2e',
'parent': 'Food',
'name': 'Sprouts'
},
'amount': '11.1',
'debit': true
},
When I do
当我做
_.filter(summary.data, {'debit': true})
I get all the objects back.
我拿回了所有的物品。
what I want?
我想要的是?
I want all the objects where category.parent == 'Food'
, how can I do that?
我想要所有对象 where category.parent == 'Food'
,我该怎么做?
I tried
我试过
_.filter(summary.data, {'category.parent': 'Food'})
and got
并得到
[]
采纳答案by idbehold
_.filter(summary.data, function(item){
return item.category.parent === 'Food';
});
回答by Akrikos
lodash allows nested object definitions:
lodash 允许嵌套对象定义:
_.filter(summary.data, {category: {parent: 'Food'}});
As of v3.7.0, lodash also allows specifying object keys in strings:
从 v3.7.0 开始,lodash 还允许在字符串中指定对象键:
_.filter(summary.data, ['category.parent', 'Food']);
Example code in JSFiddle: https://jsfiddle.net/6qLze9ub/
JSFiddle 中的示例代码:https://jsfiddle.net/6qLze9ub/
lodash also supports nesting with arrays; if you want to filter on one of the array items (for example, if category is an array):
lodash 还支持数组嵌套;如果要过滤数组项之一(例如,如果 category 是数组):
_.filter(summary.data, {category: [{parent: 'Food'}] });
If you really need some custom comparison, that's when to pass a function:
如果你真的需要一些自定义比较,那就是传递函数的时候:
_.filter(summary.data, function(item) {
return _.includes(otherArray, item.category.parent);
});
回答by evilive
beginning from v3.7.0
you can do it in this way:
从v3.7.0
你开始,你可以这样做:
_.filter(summary.data, 'category.parent', 'Food')
回答by iamyojimbo
In lodash 4.x, you need to do:
在 lodash 4.x 中,您需要执行以下操作:
_.filter(summary.data, ['category.parent', 'Food'])
(note the array wrapping around the second argument).
(注意环绕第二个参数的数组)。
This is equivalent to calling:
这相当于调用:
_.filter(summary.data, _.matchesProperty('category.parent', 'Food'))
Here are the docs for _.matchesProperty
:
// The `_.matchesProperty` iteratee shorthand.
_.filter(users, ['active', false]);
// => objects for ['fred']
回答by Denis
_.where(summary.data, {category: {parent: 'Food'}});
Should do the trick too
也应该这样做