Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
332 views
in Technique[技术] by (71.8m points)

javascript - Lodash: how do I use filter when I have nested Object?

Consider this example. I am using 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?

I tried

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

and got

[]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

lodash allows nested object definitions:

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

As of v3.7.0, lodash also allows specifying object keys in strings:

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

Example code in 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):

_.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);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...