Underscore.js - filtering in a nested Json

2019-02-20 06:49发布

I want to get all values, where the category.id = 1 so i should get 2 results

My JSON looks like this:

var test = [
            {
                "id": 1,
                "name": "name1",
                "value": "value1",
                "category": {
                    "id": 1,
                    "name": "category1"
                }
            },
            {
                "id": 2,
                "name": "name2",
                "value": "value2",
                "category": {
                    "id": 1,
                    "name": "category1"
                }
            },
            {
                "id": 3,
                "name": "name3",
                "value": "value3",
                "category": {
                    "id": 2,
                    "name": "category2"
                }
            }
        ];

my JavaScript looks like this:

var x = _.filter(test,
            function (innerObject) {
                return _.filter(innerObject,
                    function (category) {
                        return  category.id === 1;
                    });
            });

console.log(x);

I made a JS Fiddle but i get everytime all 3 elements back... not only the 2 correct ones!

I tried also something like

var x = _.where(test, {"category":{"id":2}});
console.log(x);

what seems to be logical for me, but the array is always empty

another jsFiddle

I hope somebody can tell me what i made wrong...
Thank You!

2条回答
ら.Afraid
2楼-- · 2019-02-20 07:27

This should work:

var x = test.filter(function (a) {return a.category.id === 1 })
查看更多
Juvenile、少年°
3楼-- · 2019-02-20 07:49

That's because with where you're searching for an element that is EXACTLY like {"category":{"id":1}} and your object is {"category":{"id":1,"name":"category1"}}

Try

_.filter(test, function(a){ return a.category && a.category.id === 1; });
查看更多
登录 后发表回答