繁体   English   中英

Lodash:当我嵌套Object时如何使用过滤器?

[英]Lodash: how do I use filter when I have nested Object?

考虑这个例子。 我正在使用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
        },

当我做

_.filter(summary.data, {'debit': true})

我把所有的物品都拿回来了。

我想要的是?

我想要category.parent == 'Food'所有对象,我该怎么做?

我试过了

_.filter(summary.data, {'category.parent': 'Food'})

得到了

[]

lodash允许嵌套对象定义:

_.filter(summary.data, {category: {parent: 'Food'}});

从v3.7.0开始,lodash还允许在字符串中指定对象键:

_.filter(summary.data, ['category.parent', 'Food']);

JSFiddle中的示例代码: https ://jsfiddle.net/6qLze9ub/

lodash还支持使用数组嵌套; 如果要过滤其中一个数组项(例如,如果category是数组):

_.filter(summary.data, {category: [{parent: 'Food'}] }); 

如果你真的需要一些自定义比较,那么何时传递一个函数:

_.filter(summary.data, function(item) {
  return _.includes(otherArray, item.category.parent);
});
_.filter(summary.data, function(item){
  return item.category.parent === 'Food';
});

v3.7.0开始,你可以这样做:

_.filter(summary.data, 'category.parent', 'Food')
_.where(summary.data, {category: {parent: 'Food'}});

应该做的伎俩

在lodash 4.x中,你需要做:

_.filter(summary.data, ['category.parent', 'Food'])

(注意数组包围第二个参数)。

这相当于调用:

_.filter(summary.data, _.matchesProperty('category.parent', 'Food'))

以下是_.matchesProperty的文档

// The `_.matchesProperty` iteratee shorthand.
_.filter(users, ['active', false]);
// => objects for ['fred']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM