簡體   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