Underscore.js - filtering in a nested Json

2019-02-20 07:09发布

问题:

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!

回答1:

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


回答2:

This should work:

var x = test.filter(function (a) {return a.category.id === 1 })